How to correctly change sprite on a prefab clone?
Hello Community, I have made a script so that when the Linecast between the mouse cursor and the player hits a gameobject ("Int_Molecule") it changes its sprite into a new one.
public class CursorXhair : MonoBehaviour
{
public Player Player;
public AttachmentController Molecule;
//public SpriteRenderer spriteRenderer;
public Sprite newSprite;
public Sprite originalSprite;
// Update is called once per frame
void Update()
{
Vector2 playerPos = Player.transform.position;
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = mousePos - playerPos;
transform.position = mousePos;
Debug.DrawRay(playerPos, direction);
RaycastHit2D mouse2Player = Physics2D.Linecast(mousePos, playerPos);
if (mouse2Player.collider != null && mouse2Player.collider.tag == "Int_Molecule")
{
Debug.Log("mouse2Player is colling");
Molecule.spriteRenderer.sprite = newSprite;
}
else
{
Molecule.spriteRenderer.sprite = originalSprite;
Debug.Log("mouse2Player is NOT colling");
}
}
}
Since I need multiple clones instantiation of this same object I create this script and assign it to a LevelManager. So I create a prefab as the original object to instantiate. The Linecast works as expected as you can see in the two images, however the clones do not update the sprite as expected. Interestingly the prefab in the prefab folder does update (see the last image), but the update is not reflected in the running game and the clones instantiations.
public class MoleculeInstantiator : MonoBehaviour
{
public GameObject molecule;
//public Transform moleculeLocation;
// Start is called before the first frame update
void Start()
{
Instantiate(molecule, new Vector2(-1, 6), Quaternion.identity);
Instantiate(molecule, new Vector2(-11, 2), Quaternion.identity);
Instantiate(molecule, new Vector2(9, -6), Quaternion.identity);
Instantiate(molecule, new Vector2(14, 3), Quaternion.identity);
Instantiate(molecule, new Vector2(-14, -7), Quaternion.identity);
Instantiate(molecule, new Vector2(-17, 6), Quaternion.identity);
Instantiate(molecule, new Vector2(17, -9), Quaternion.identity);
}
}
Is there something I am doing wrong or in the wrong order?
I am thinking that the best way would be to have the two scripts above as one attached to the prefab (and therefore the clones), but I preferred to keep the two scripts separated for better tidiness.
Would that solve it or am I missing the point?