You would just use .GetComponent<TYPE>() where TYPE is the component you want to access. For a game object with a spriter render attached this would be SpriteRender and for a UI object it would be Image I believe. From there you could directly talk about the sprite property.
Are you sure it’s the prefab you wish to change and not just the instantiated object? I’m not sure if you can edit prefabs directly at run time and even if you can I image it’s best to avoid doing so.
In your code snippet temp would reference the instantiated object. You’d want to add a public variable of type Sprite to the prefab code and attach the sprite you want to change to then you could change the sprite of it with
public Sprite newSprite; //This is declared at the top
//Your other code here
temp.GetComponent<SpriteRenderer>().sprite = newSprite;
Lesson 86 covers this where you flick through sprite array positions via script. The basics of it are that you define a Sprite array which it sounds like you’ve already done
where spriteIndex is an int for the sprite you’re looking for in the array, remember an array starts at 0 so if you’ve got 4 sprites then it’s 0-3 to call each of them.
Hmm, i try and try but somethings don’t work.
The SpriteRender component take the right sprite, i see that on run, but i want that sprite to be on my component Image’s “Source Image”
Now im thinking that maybe my Image (called “Type”) need a script component to manage the Sprite image, but i dont recognize how. So if i do this i can search for the parent’s component SpriteRender and apply it.
I link the structure of my object:
Attached components:
My obj Class
public class TypeIcon : MonoBehaviour
{
public Sprite[] typesprites;
private string typeName;
Sprite icon;
//private void Start()
//{
// Setting(typeName);
//}
public void Setting(string nam, int i)
{
this.typeName = nam; print(typeName);
this.GetComponentInChildren<SpriteRenderer>().sprite = typesprites[i];
}
The way i create the obj (Is a function inside windows canvas component):
public void PrintSingleType(Vector3 pos)
{
GameObject efficacia = Instantiate(typeIcon, pos, Quaternion.identity) as GameObject;
efficacia.transform.SetParent(transform);
efficacia.transform.position = pos;
If you’re using a UI image as opposed to a game object with a sprite renderer the component you wish to access is an Image instead of a SpriteRenderer so
GetComponent<Image>().sprite = typesprites[i];
You could also call the setting at the instantiate point so that you have efficacia.Setting("text",i); as opposed to doing it in the start method.