- Home /
Question by
martijnvanginkel · Oct 21, 2017 at 01:08 PM ·
booleanchild-to-gameobjectfindobjectsoftype
Why is the bool only true for the first object
I'm making a game where you can wield light such as torches and lanterns. I made a script I can pass on each object:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LightController : MonoBehaviour {
public PlayerController thePlayer;
public bool inLightRange;
public bool holdingLight;
public bool isLantern;
public bool isTorch;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (this.transform.parent == thePlayer.transform) {
holdingLight = true;
}
if (this.transform.parent != thePlayer.transform){
holdingLight = false;
}
if (inLightRange && Input.GetKeyDown (KeyCode.LeftAlt) && holdingLight != true) {
this.transform.parent = thePlayer.transform;
this.GetComponent<Renderer> ().enabled = false;
}
if (holdingLight && Input.GetKeyDown (KeyCode.LeftAlt)) {
this.transform.parent = null;
this.GetComponent<Renderer> ().enabled = true;
}
}
void OnTriggerEnter2D (Collider2D other) {
if (other.CompareTag ("Player")) {
inLightRange = true;
}
}
void OnTriggerExit2D (Collider2D other) {
if (other.CompareTag ("Player")) {
inLightRange = false;
}
}
}
So I pass this information to the player:
// If player is in the dark, use Respawn
isInLight = Physics2D.IsTouchingLayers (myCollider, whatIsLightsource);
// Check for each Object with LanternController if its being held
foreach (LightController light in lights) {
if (light.holdingLight == true) {
if (light.isLantern) {
holdLantern = true;
}
if (light.isTorch) {
holdTorch = true;
}
}
if (light.holdingLight == false && isInLight) {
if (light.isLantern) {
holdLantern = false;
}
if (light.isTorch) {
holdTorch = false;
}
}
}
if (holdTorch == false && holdLantern == false && isInLight != true) {
levelManager.RespawnPlayer ();
}
// Animations
myAnimator.SetFloat ("Speed", Mathf.Abs(myRigidbody.velocity.x));
myAnimator.SetBool ("Grounded", grounded);
myAnimator.SetBool ("HoldLantern", holdLantern);
myAnimator.SetBool ("HoldTorch", holdTorch);
So the code is working but not when I make a duplicate of a torch or lantern. The bool 'holdingLight' in the playerscript is not working on duplicates. why is it only working on the first object?
Comment