- Home /
How to change UI image with a name to a different image with a name
Hi, I'm trying to make FClickCharacter() a program to fire when you click on a button. FrogImage is an image I assign by dragging and dropping because I made it [SerializedField].
"SelectedCharacter" is a different script that contains "sprite1" which is the image of a UI image. I want to make it so that when FClickCharacter is fired, it changes sprite1 to equal the image of FrogImage so that the UI image's source image changes to equal FrogImage.
When I run the code below, I get an error message saying "the name 'spr' does not exist in the current context". I know that there is probably going to be more to be done after I fix this first problem, like using the right syntax instead of "spr.Sprite = FrogImage".
[SerializeField] public Sprite FrogImage;
void Start()
{
spr = GetComponent<SelectedCharacter>().sprite1;
}
public void FClickCharacter()
{
spr.Sprite = FrogImage;
}
Answer by mischkom · Aug 20, 2021 at 04:50 AM
Firstly, you do not need [SerializeField] if it is only for viewing it in the inspector, since its already a public variable. Not that it matters much in this context but I thought you might want to know. Secondly, spr does indeed not exist in that context. You did not declare it anywhere outside of a method body.
public Sprite FrogImage;
void Start()
{
}
public void FClickCharacter()
{
GetComponent<SelectedCharacter>().sprite1 = FrogImage;
}
is how I would do it.
Answer by joan_stark · Aug 24, 2021 at 07:14 PM
public class SomeClass : MonoBehaviour
{
//You have two options, first make it public field if you may modify this from another script.
public Sprite frogSprite;
//Or you can make it private if you want to avoid that other scripts can modify your frog sprite, but you can still drag and drop an image from inspector.
[SerializeField] private Sprite frogSprite;
//Cached component for better performance.
private SelectedCharacter _selectedCharacter;
private void Awake()
{
//Cache Selected character component, so it doesn't impact on performance in runtime.
_selectedCharacter = GetComponent<SelectedCharacter>();
}
public void FClickCharacter()
{
_selectedCharacter.sprite1 = frogSprite;
}
}