Categories
Development Unity

Change color of individual prefab instance after it was touched Unity 2d

I started making a 2d game, where an Individual Prefab Instance has to change color after being touched. I’m new to programming in C# and I’ve scoured the internet for hours but I still can’t find an answer which works. I tried adding GetComponent<Renderer>().material.color = Color.red; to the script on my prefab but it changes the color of all instantiated prefabs. My Unity version is 2019.2.3f1. Please help me.

Here’s the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TouchDetector : MonoBehaviour
{
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                 if (hit.transform.name == "square")
                 {
                      Destroy(gameObject);
                      print("TOUCHED");
                      GetComponent<Renderer>().material.color = Color.red;
                 }
            }
        }
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *