- Home /
Can't do something while bool is true even if accessing other script.(C#)
l have 3 objects and 2 scripts. This is what first script does: When object A (Player) collides with object B (Ground), it sets bool called collided to true. using UnityEngine; using System.Collections;
public class changegrav : MonoBehaviour {
public bool collided;
void Update () {
Debug.Log (collided); // I USED THIS TO CHECK IF SCRIPT WORKS PROPERLY, AND IT WORKED
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject.name == "tground") {
collided = true;
}
}
void OnTriggerExit (Collider other)
{
if (other.gameObject.name == "tground") {
collided = false;
}
}
}
And my second script is attached to object C, and it supposed to play an animation if collided = true:
using UnityEngine;
using System.Collections;
public class changegrav2 : MonoBehaviour {
public GameObject objectOne;
private changegrav otherScript;
private bool collided;
void Start (){
otherScript = objectOne.GetComponent<changegrav> ();
collided = otherScript.collided;
}
}
After realizing that its not working, l decided to remove Debug.Log from the first script and add it to the second script and l realized even if collided in first script is true, Debug.Log in second script always prints collided as FALSE . Its probably because l didn't called collided bool from script 1 to script 2 properly...maybe... ldk. If you have any ideas, plz let me know.
$$anonymous$$aybe because you call it in Start()? Call "collided = otherScript.collided" in Update(). You can then say: if (collided) do
Generally you could also say directly:
if (otherScript.collided) do
Thank you so much, changing if(collided == true) to if(otherScript.collided == true) worked well.
Answer by Lazarus-Overman · Aug 16, 2017 at 02:27 AM
Change the bool in your first script to : public static bool collided. Then, in the second script, just have :
void Update (){ if (changegrav.collided == true){ blah, blah, blah; }
By making a bool static in the first script you can easily check its status in any script as I did above. The blah, blah part would be your animation instructions. Good luck.
Sorry, you need another "}" at the end to make it work properly.
Your answer
Follow this Question
Related Questions
Unity3D: Entering a trigger disables a few bools for no reason 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do i Achieve mesh Extrusion? 2 Answers
Can I make a collider ignore only one other collider? 0 Answers