- Home /
Script to change SpriteRenderers sprite field
I am creating a simple 2D door, when i stand in my trigger, i want it to open by switching texture from the open door texture to the closed one. I got it working with an animator where i had the transition between the textures occur when i entered and left the trigger area, but i wanted too see if it's possible to achieve the same result with script only. I do not want to do it with 2 GameObjects however, i got that working too by toggling the enable on the spriteRenderer.
Is there anyone who can help me? I'm pretty new to coding, but I have searched everywhere and not found a single solution that matches what i want.
Answer by Fabulous-Design · Jul 27, 2014 at 02:22 PM
var sprite1: Sprite;
gameObject.GetComponent(SpriteRenderer).sprite = sprite1;
using UnityEngine;
using System.Collections;
public class openDoorCode : $$anonymous$$onoBehaviour
{
SpriteRenderer renderer;
Sprite Open;
Sprite Closed;
void Start()
{
Open = Resources.Load<Sprite>("Door_Open");
Closed = Resources.Load<Sprite>("Door_Closed");
renderer = GetComponent<SpriteRenderer>();
}
void FixedUpdate()
{
}
void OnTriggerEnter2D(Collider2D Collider)
{
renderer.sprite = Open;
print("Open");
}
void OnTriggerExit2D(Collider2D Collider)
{
renderer.sprite = Closed;
print("Close");
}
}
This is my code so far, as of now, both when i enter and exit the area, it sets the renderer.sprite to none. What am I missing? And thank you for your help, much appreciated :)
and in C#
Sprite sprite1;
gameObject.GetComponent<SpriteRenderer>().sprite = sprite1;
Well, I couldn't get the Resources.Load to work on my own so i made the Sprite public and assigned it in the inspector. Works like a charm ;)!
SpriteRenderer render;
public Sprite Open;
public Sprite Closed;
void Start()
{
render = GetComponent<SpriteRenderer>();
}
void FixedUpdate()
{
}
void OnTriggerEnter2D(Collider2D Collider)
{
render.sprite = Open;
}
void OnTriggerExit2D(Collider2D Collider)
{
render.sprite = Closed;
}
}
Answer by TallBrian · Mar 05, 2017 at 03:27 PM
The resources need to be in a folder named "Resources" in your project. PNG files in the Assets folder are not found. I was getting nothing (like you) until I made a folder called "Resources" put copies of my PNGs in then. Then it worked like great. see: "Loading Resources at Runtime"
Your answer
Follow this Question
Related Questions
Sprite Renderer changes visible position on being assigned to a sprite 1 Answer
Sprite Renderer is wrapping bottom pixel when it shouldn't be 1 Answer
How to instantiate object as child of another element 1 Answer
Gui.Box - Sprite 0 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers