- Home /
How to Image Swap on Collision
Hey guys so Im working on a 2D Platformer. I have a small cabin that represents the end of my level (when the player walks in the door, the level is over). I have two images, One is of the cabin with the door closed, the second is the same image but with the door open. How would I make it that when the player reaches a certain point of the cabin (say two feet before the door), the image swaps to the second pic with the cabin door open (to make it look like the door opens for the player)? Im guessing I would use a collider with maybe "Is Trigger" marked but Im still not sure exactly how to incorporate it. Here is the code I have so far:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Cabin : MonoBehaviour {
Image myImageComponent;
public Sprite myFirstImage; //Drag your first sprite here in inspector.
public Sprite mySecondImage; //Drag your second sprite here in inspector.
void Start() //Lets start by getting a reference to our image component.
{
myImageComponent = GetComponent<Image>(); //Our image component is the one attached to
this gameObject.
}
public void SetImage1() //method to set our first image
{
myImageComponent.sprite = myFirstImage;
}
public void SetImage2()
{
myImageComponent.sprite = mySecondImage;
}
I attach this to my first Cabin image (the default one) and set it as myFirstImage in the Inspector, and the second image goes to mySecondImage. I made a box collider where I want it and im sure that needs to be added to my code somewhere. Would I do "On Collision" or something. Any help is greatly appreciated!
Answer by cstooch · Jul 12, 2017 at 09:13 PM
I would use OnTriggerEnter for your change to the open door, and OnTriggerExit to change back to the door closing (if that's actually needed).
(And check is trigger)