- Home /
Deactivating a Child in C#
Hello, I am new to scripting and I am trying to learn a javascript/C# by practicing a bit. I am working on a small trial & error project :P . what I am trying to do is pretty much:
click on an object and deactivate it click on it and activate it (gameObject.active = true/false). Obviously what doesn't work is the fact that once the object is deactivated you can't click on it to activate it again. So the idea is to have the object as a child and when I click on the parent i can activate/deactivate it. Sorry for the noob-ish question but I've read a lot of the documentation & posts and I can only get more confused everytime I try to find an answer!.
As you can see from the script I am detecting the collider I hit and then (de)activate its gameObject. How do I change from collider.gameobject.active to something like collider.gameobject.child.active? In other words how can I access and (de)activate the child for the game object I am raycasting on?
Many thanks
Here is the script so far:
using UnityEngine;
public class RayCast : MonoBehaviour { void Update () { if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit;
if(Physics.Raycast(ray, out hit)) {
Debug.Log(hit.collider.name);
if(hit.collider.gameObject.active == true)
hit.collider.gameObject.active = false;
else hit.collider.gameObject.active = true;
}
}
}
}
Answer by skovacs1 · Nov 22, 2010 at 11:23 PM
To act on children, you would loop through them in the transform like so:
using UnityEngine;
public class clickActivation: MonoBehaviour { RaycastHit hit; void Update () { if(Input.GetMouseButtonDown(0) && Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit)) { Debug.Log(hit.collider.name); foreach(Transform child in hit.transform) child.gameObject.active = !child.gameObject.active; } } }
Children are stored in the Transform. See this doc.
This worked!. Thank you for the quick reply and the !child... freebie as well :). I tottally forgot how to get the "opposite" of the current value....
Your answer
Follow this Question
Related Questions
Destroying a child object? 1 Answer
How to activate the child of an object without declaring a public transform? 1 Answer
Make a simple tree 1 Answer
Most effective way to get deactivated children? 1 Answer
child object to parent c# 1 Answer