I am trying to change the texture associated with a gameobject programaticlly and tried:
switch (health)
{
case 5:
gameObject.SpriteRenderer.sprite = health5;
break;
case 4:
SpriteRenderer.sprite = health4;
break;
But I get an error with both of these. The top one being CS1061 UnityEngine.GameObject does not contain a reference and the second being CS 0120 An object reference is required to access non static member UnityEngine.SpriteRenderer.sprite.
What am I missing here?
You need to use GetComponent.
–Eric
I am new to GetComponent, how would I call this? I tried:
switch (health)
{
case 5:
GetComponent<SpriteRenderer.sprite>() = health5;
break;
But it gave me a CS0131 The left hand side must be a variable, property, or an indexer error.
JavaScript:
GetComponent (SpriteRenderer).sprite = health5;
C#:
GetComponent<SpriteRenderer> ().sprite = health5;
Javascript should be “GetComponent(SpriteRenderer).sprite”. The generic version is slower (and kinda ugly) and has no benefits over the standard version, so don’t use it.
–Eric
I’ve been using C# for too long!
Thanks for the correction, and I’ve updated my post.
Again, thank you for the clarification!