- Home /
Add event listener to referenced prefab Child
I have a childObject that i want to have a event listenner when onMoueUp is executed, i made the configuration bellow but the desired behaviour is not achieved.
On a GameObject i have a reference to a preFab GameObject. This Prefab GO has a collider that isTrigger and the code for this preFab is the following
using UnityEngine;
using System.Collections;
public class Clickable : MonoBehaviour {
public delegate void ClickAction();
public event ClickAction onClicked;
void OnMouseDown() {
if(onClicked != null){
Debug.Log(" HAS CLICK");
this.onClicked();
}
else{
Debug.Log("NO CLICKLISTENER");
}
}
}
On the parent i have the following:
using UnityEngine;
using System.Collections;
public class VehicleRenderer : MonoBehaviour {
public float posX,posY,posZ;
public GameObject vehicle;
public string vehicleName;
// Use this for initialization
void Start () {
Quaternion spawnRotation = Quaternion.identity;
Vector3 spawnPosition = new Vector3 (posX,posY, posZ);
//Create the prefab
Instantiate (vehicle, spawnPosition, spawnRotation);
Clickable clickable=vehicle.GetComponent<Clickable>();
clickable.onClicked+=vehicleClicked;
}
// Update is called once per frame
void Update () {
}
void vehicleClicked(){
Debug.Log(vehicleName + " Clicked");
}
}
When i click NO CLICKLISTENER is always logged, and the VehicleRenderer click is never invoked
Answer by Utamaru · Mar 19, 2015 at 12:19 PM
You're getting script from prefab, not from actual instantiated gameObject. Fixed code:
// Save instantiated gameObject to variable
GameObject vehicleObj = Instantiate (vehicle, spawnPosition, spawnRotation);
// And get Clickable component from it
Clickable clickable = vehicleObj.GetComponent<Clickable>();
Thank you, that was it i would never realize by myself
Your answer
Follow this Question
Related Questions
Why doesn't unregistering an anonymous delegate trigger an error? 1 Answer
Login form: Do I have to set custom delegates to null in OnDestroy? 0 Answers
Persistent listeners for Button.onClick are removed at runtime, if buttons are instances of prefab 1 Answer