binoculars
binoculars

Reputation: 2274

How to add listener to UnityEvent in prefab programatically

I read about UnityEvent and am trying to implement it.

I have a "GameController.cs" script, attached to a GameObject "ScriptsHolder", and a "target.cs" script attached to a Prefab GameObject called "target".

"target" is not in the scene on startup: I initiate multiple targets at a certain point, which are renamed to "target0", "target1", ...

When a target receives damage, I want it to send its name to GameController.cs, which has a void that destroys that object. Here's what I did:

target.cs:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Events;

 public class target : MonoBehaviour {

      public UnityEvent damageEvent;

     void Damage(float damage)
     {
         damageEvent.Invoke();
     }        
 }

Next, I click on my target Prefab and in the inspector, I try to add "ScriptsHolder" to the Damage Event. Here's my problem: I can't drop the ScriptsHolder in the Damage Event. Did some testing, and the reason for this appears to be the fact that "target" is not yet in my scene.

So I read about adding a listener instead, but I can't figure out how to do this.

Here what I have in "GameController.cs":

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Events;
 public class GameController : MonoBehaviour {
 UnityEvent damageEvent;
 void Awake()
 {
     damageEvent.AddListener(targetReceivedDamage);
 }
 void targetReceivedDamage()
 { // do some stuff }
 }

But that doesn't work. What am I doing wrong? Or how can I add the ScriptsHolder to the Damage Event even though "target" isn't inside the scene?

Any help is much appreciated!

Upvotes: 0

Views: 6676

Answers (1)

Umair M
Umair M

Reputation: 10750

You need to add listener when you instantiate target object. For example:

Change your prefab declaration to Target type and reassign target prefab in the inspector.

public Target targetPrefab;

then

Target target = Instantiate(targetPrefab);

target.damageEvent.AddListener(targetReceivedDamage);

Hope this helps :)

Upvotes: 5

Related Questions