Search code examples
c#unity-game-engineeventsgame-enginegame-development

Unity: error when trying to invoke an event


I want to trigger an event whenever the player collides with another object, and made the event in the EventManager script, referenced it in the player script, subscribed to it the "onCollision" method but when i try to invoke it in the "OnCollisionEnter2D" method it throws me an error like i would need to subscribe it, and i cant figure out why. How could i invoke it properly? I looked in the tutorials and documentation but i dont understand what i'm doing wrong..

the error: PlayerScript.cs(42,21): error CS0070: The event 'EventManager.onCollisionDo' can only appear on the left hand side of += or -= (except when used from within the type 'EventManager')

EventManager script:

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

public class EventManager : MonoBehaviour
{
    public event onCollisionDo_dlg onCollisionDo;
    public delegate void onCollisionDo_dlg();
   
}

Player script:

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

public class PlayerScript : MonoBehaviour
{

    public float speed = 10;
    private Rigidbody2D body;
    private Vector2 Movement;
    [SerializeField]
    private GameObject EventManager_reference;     // reference to the EventManager via inspector 
    private EventManager EventMS;                  // reference to the EventManager script


   
    void Start()
    {
        body = GetComponent<Rigidbody2D>();
        EventMS = EventManager_reference.GetComponent<EventManager>();
        EventMS.onCollisionDo += onCollision;
    }

    
 void Update()
    {
        Movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    }

 private void FixedUpdate()
    {
        body.MovePosition((Vector2)transform.position + (Movement * speed * Time.deltaTime));
    }
 private void onCollision()                             // Method to execute when event triggered
    {
        print("it collided");          
        
    }
 private void OnCollisionEnter2D(Collision2D temp)
    {
        EventMS.onCollisionDo?.Invoke();                  // Here is the problem 
    }
}

Solution

  • Reason behind the issue

    The error appeared due to having the event invoked outside the class it was in.
    More info: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/event

    Potential solution

    If you want to be able to invoke your delegate outside the EventManager class, remove the event keyword or add a public method that would allow to invoke the event using an another way.

    Extra note

    In this case you can use a built in delegate called Action instead of making a custom one.