- Home /
detect collision on child
hi everybody, i am trying to figure out one thing, that seemed easy at first, though i am just a beginner.
i want to have only one script in the parent gameobject, and i will have four child and i want to detect when user clicked any of the children...is this possible without having scripts for every child?
Answer by Tetrad · Jun 19, 2010 at 04:22 PM
Sure it's possible, but it would be a lot easier if you put scripts on them. You can even put scripts on children dynamically.
If you wanted to do it without child scripts, you would simply iterate over your children and then do a raycast on their collider with the screen point to ray.
However, if you wanted to let unity handle it, and do dynamic child scripts, here's one (slightly advanced) way to go about doing it.
Parent class:
void Awake() { foreach( Transform childTransform in transform ) { ChildClass childClass = childTransform.AddComponent<ChildClass>(); childClass.TouchDelegate = OnTouchedChild; } }
void OnTouchedChild( GameObject childObject ) { Debug.Log( "touched child " + childObject.name, childObject ); // do whatever }
Child class (let's say it's called ChildClass
, but you can name it whatever as long as it's updated in the parent class script):
public delegate void OnTouchedDelegate( GameObject touchedObject );
OnTouchedDelegate touchDelegate; public OnTouchDelegate TouchDelegate { set { touchDelegate = value; } }
void OnMouseDown() // monobehaviour method { touchDelegate( gameObject ); }
You might want to put some error handling in there, like maybe check to see if the touch delegate is not null if that's a case you want to handle, or if the child object has a collider before adding the script, or whatever your specific needs are.
doing that easy you should cast a ray and see who is colliding with the ray. cast the ray using the functions that tetrad said but hey the advantage of unity is it's aggregation system and components so use the second method that he said unless there is a good reason.
one thing tho for reference, addComponent only works using gameObject reference and on the ChildClass, it's public OnTouchedDelegate ( not on touchDelegate). then it all works fine.
@Jesse How well does raycasting perform? I would like to choose the most optimal of these two choices. I am more comfortable with the raycasting approach except I am unsure as to what the consequences are. Cheers
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
Ignore parent Rotation 1 Answer
Instantiated GameObject collision without script repetition? 1 Answer
Child object not moving with parent 0 Answers