Can one add events to an instantiated object?

Hello community,

Just starting on unity and I was wondering if it was possible to add event listeners to objects that were instanciated:

var bullet : GameObject;

function Update () {
	if(Input.GetButtonUp('Jump')){
		bullet = GameObject.Instantiate(bullet, this.transform.position, this.transform.rotation);
		bullet.rigidbody.AddRelativeForce(Vector3(2000,0,0));
		
		// this is what I would like to do:
		bullet.on('collisionEnter', function(coll: Collider){
			Debug.Log('ok');
		});
	}
}
}

Or is the only way to create a script for the bullet behaviour itself?

My main interest would be to apply different listeners according to a given parameter.

Thanks

1 Answer

1

Step 1. Use c# so you can define events (JS can only subscribe to event IIRC).

Step 2. Create an event in your bullet class.

public class MuhBullet : MonoBehaviour 
{
	public string BulletId;
	
	public event Action BulletCollided; //event using the default Action delegate
	
	public Delegate void CollisionWithDataDelegate(Collision collision, string name)
	public event CollisionWithDataDelegate BulletDataCollision; //example with custom delegate
	
	void OnCollisionEnter(Collision collision) 
	{	
		if (BulletCollided!=null) BulletCollided(); //Raise event, if subscribers
		
		if (BulletDataCollision != null) BulletDataCollision(collision, BulletId); //Raise a different one that has data, if subscribers
	}
}

Step 3. Subscribe to event.

bullet = GameObject.Instantiate(bullet, this.transform.position, this.transform.rotation);
bullet.BulletId = "Bill";

bullet.BulletCollided += DoSomethingOnBulletCollision;
bullet.BulletDataCollision += DoSomethingWithData;

bullet.rigidbody.AddRelativeForce(Vector3(2000,0,0));

//somewhere else
public void DoSomethingOnBulletCollision()
{
    Debug.Log("Bullet collided!");
}

public void DoSomethingWithData(Collision collision, string name)
{
    Debug.Log("A bullet of the following name collided: " + name);
}

Step 4. Do cool things and be happy.

c# it is then :)

That's the way to go with Unity IMHO. Unity's JS is their own beast that is useless outside of Unity (whereas c# is actually used, a lot ). It's definitely worth the (tiny) learning curve of a different syntax. Unity JS has to be learned anyhow by anyone new to it (since it isn't actually javascript), so might as well learn the language that is useful outside of Unity.