Question by
Gentatsu · Feb 07, 2017 at 01:24 PM ·
childevent handlers
Add an event listener when GameObject becomes a child of another
I'd like to have a listener on my gameobject for when it becomes a child of another gameobject, so I can perform functions based on what it's added to.
Any good of way of doing it, or is this a silly thing to do anyway?
Comment
Best Answer
Answer by nasir_41 · Feb 07, 2017 at 01:33 PM
bool isEvenFired=false;
public delegate void IsChild(bool status);
public event IsChild ChildEvent;
void Update(){
if(!isEventFired){
isEventFired=true;
if(ChildEvent!=null){
ChildEvent(transform.parent!=null);
}
}
}
And in other scripts you just need to assign a method to this delegate and event will be fired.. Hope this will give you a quick idea about it.
Is there a way to do it without it being in an Update function? That's one of the things I was trying to avoid! Thanks!
Yes use this $$anonymous$$ethod void OnTransformParentChanged(){ }
See the docs https://docs.unity3d.com/ScriptReference/$$anonymous$$onoBehaviour.OnTransformParentChanged.html