Home > Back-end >  Unity script only working on one gameobject
Unity script only working on one gameobject

Time:08-19

This script in short changed the color of the gameobject it's attached to when the bullet goes through it. `

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

public class targetHit : MonoBehaviour
{
    public Material oldMat;
    public Material newMat;
    Renderer rend;

    // Start is called before the first frame update
    void Start()
    {
        rend = GetComponent<Renderer>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "bullet")
        {
            hitTarget();
        }
    }

    void hitTarget()
    {
        rend.material = newMat;
        StartCoroutine("waitThreeSeconds");
    }

    IEnumerator waitThreeSeconds()
    {
        yield return new WaitForSeconds(3);
        rend.material = oldMat;
    }
}

`

However it only works on the game object highlighted in the image attached. Image

CodePudding user response:

because rend = GetComponent(); called in Start, if image not attached to Gameobejct, rend will be null. so without image component, this script now work.

CodePudding user response:

Assuming you assigned the material files in the inspector, instead of assigning the "rend" variable on start, try instead assigning it the same way, for all GameObjects that use the script. Please let me know if this does not work.

  • Related