Changing sprite colours using events

Hey all!

I’m still quite new to C# and all its intricacies so sorry for this noob question.

I am trying to implement a mechanic for an endless runner where, upon button press, the player changes colour in order to phase through gates and obstacles.

However, in the early stages of getting this to work, I can’t seem to get my player to change colours.

Attached is my colour shift script and the event manager script I am using at the moment.

Colour Change Script:

using UnityEngine;
using System.Collections;

public class ColourChangeScript : MonoBehaviour {

    private SpriteRenderer objectSprite;
    private Color blue = new Color (0, 0, 1, 1);
    private Color red = new Color (1, 0, 0, 1);

    void Start ()
    {       
        objectSprite = GetComponent <SpriteRenderer> ();
        objectSprite.color = blue;
        Debug.Log ("Colour has been set");
    }


    void OnEnable()
    {
        EventManager.OnClicked += ColourShift;
        Debug.Log ("Subscribed");
    }
       
    void ColourShift ()
    {
        if (objectSprite.color == red)
        {
            objectSprite.color = blue;   
            Debug.Log ("Colour has changed!");
        }
            else if (objectSprite.color == blue) {
            objectSprite.color = red;
            Debug.Log ("Colour has changed!");
        }
    }

    void OnDisable ()
    {
        EventManager.OnClicked -= ColourShift;
        Debug.Log ("Unsubscribed");
    }
}

EventManager Script:

using UnityEngine;
using System.Collections;

public class EventManager : MonoBehaviour {

    public delegate void ClickAction ();
    public static event ClickAction OnClicked;

    void ButtonPress ()
    {
        if(Input.GetButtonDown ("Jump") == true)
        {
            Debug.Log ("Button did work");
            if(OnClicked != null)
                OnClicked();
        }

    }
}

Any help would be massively appreciated!

I don’t see anything immediately wrong with this, but I also don’t use dot net events, I use UnityEvent. What are you seeing print out in the console?

On your EventManager script are you calling ButtonPress() from another MonoBehaviour’s Update method or do you have it linked to a Unity UI button press in the editor? Input.GetButtonDown will only return true on the frame that the key was pressed. So if you’re not checking for the jump button keystroke in an Update loop your code will never execute.