C# errors in Unity

2020-05-09 22:29发布

问题:

I'm having script errors. But first what I'm doing.

I'm making my text colorful, the system should look like this. Every second, new differet color. But I scripted the code and it shows errors. Like:

error CS0619: UnityEngine.Component.renderer' is obsolete:Property renderer has been deprecated. Use GetComponent() instead. (UnityUpgradable)'

error CS1061: Type UnityEngine.Component' does not contain a definition formaterial' and no extension method material' of typeUnityEngine.Component' could be found (are you missing a using directive or an assembly reference?)

Also the script is this.

using UnityEngine;
using System.Collections;

public class Colors : MonoBehaviour

{
    public float timer = 0.0f;

    void Start()
    {

    }


    void Update()
    {
        timer += Time.deltaTime;
        if (timer >= 2.0f)//change the float value here to change how long it takes to switch.
        {
        // pick a random color
            Color newColor = new Color(Random.value, Random.value, Random.value, 1.0f);
        // apply it on current object's material
            renderer.material.color = newColor;
            timer = 0;
        }
    }
}

回答1:

You can no longer access renderer.material.color directly anymore starting from Unity 5 up. you must use GetComponent<Renderer>(); to get the component of the GameObject first, then you can access the material from the Renderer.

public float timer = 0.0f;
 Renderer rd;

 void Start()
 {
     rd = gameObject.GetComponent<Renderer>();
 }


 void Update()
 {
     timer += Time.deltaTime;
     if (timer >= 2.0f)//change the float value here to change how long it takes to switch.
     {
         // pick a random color
         Color newColor = new Color(Random.value, Random.value, Random.value, 1.0f);
         // apply it on current object's material
         rd.material.color = newColor;

         timer = 0;
     }
 }