Problem with Swap Image in Unity 5 with C#.

Hi everyone.

I my demo, I need when the player enter a “trigger”, the UI image on screen change from one image to other, something like “you crossed a line” sort of. The problem is I don’t know how to do that by C# script, using the new Canvas.

In older versions of Unity, that was easy using GUI Texture, but this tool seems no working on Unity 5 any more. I google, I dig in forums over the net, but the few info available is confusing and non-existen samples to how manipulate images-canvas with code.

Hope someone help. What should be a simple task, its been a NIGHTMARE for almost a week and keep me stuck.

void OnTriggerEnter(Collider other)
{
if(other.tag == “Player”)
{
print(“Tank has crossed”);
//show new image intead of the older one.
}

}

}

Just use another UI image at the exact same place and when you enter the trigger just set the current one to SetActive(false) and the other one to SetActive(true). And when you exit the trigger you can do something similar to go back.

Hi Abhiroop Tandon.

In fact, using “SetActive(true)” didn´t work either. Not sure why, maybe Unity doesn´t recognize canvas-image as GameObject. This is what finally works well:

public Sprite miImageTwo;
public Image imageUI;

void OnTriggerEnter(Collider other)
{
if(other.tag == “Player”)
imagenUI.sprite = miImageTwo;
}

In perspective:

1.- Put “UnityEngine.UI” at the top of the script (library UI).
2.- Create the public image variable in that script.
3.- Put the desired image in the Hierarchy by canvas.
4.- In the GameObject in Hierarchy, drag the image-canvas to the inspector in the slot given by the script.
5.- Test!

Thanks for your comments! :smiley: