- Home /
C# Disable gameObject not working. Help?
Hello there, I have a script I'm working on that enables a game object when the player enters a collision area, (so on trigger) and disables when the player leaves the collision area.
It is meant for objects on NPCs to only become active when the player is within the collision area otherwise the objects are gone.
My code looks like this:
public GameObject stuff;
void OnTriggerEnter (other : Collider) {
if (col.gameObject.tag == "Player") {
stuff.enabled = true;
} else if (col.gameObject.tag != "Player") {
stuff.enabled = false;
}
}
}
the idea is to have any object in the "stuff" parameter to enable/disable depending on the player's collision with NPC's collider. I'm hoping someone out there, may be of some help. Thank you for your insight in advance.
Answer by InfiniBuzz · Jul 14, 2015 at 03:27 PM
Hi! As you said you want the stuff-Object to be disabled wehen the Player leaves the collision area so you also need to implement the OnTriggerExit() Method.
public GameObject stuff;
...
// In C# you need to use this instead of other : Collider
void OnTriggerEnter (Collider other) {
if (other.gameObject.tag == "Player") {
stuff.SetActive(true); // stuff.enabled = true; depending on version
}
}
void OnTriggerExit (Collider other) {
if (other.gameObject.tag == "Player") {
stuff.SetActive(false); // stuff.ebabled = false; depending on version
}
}
Also make sure the collider of the Object this script is attached to is set as trigger. You also need to check the tag of the other
object, the object col
is not present as far as I see.
Thank you so much for this! It has since helped me create my own AOE scripts and I'm thankful for that!
Your answer
Follow this Question
Related Questions
Can't click gameobject when over another trigger? 1 Answer
Trigger Respawn 3 Answers
solution with on trigger destroy 0 Answers
Restraining movement to camera bounds 1 Answer
Shuttle Runs & Counter 0 Answers