【问题标题】:C# errors in UnityUnity 中的 C# 错误
【发布时间】:2016-10-12 09:12:11
【问题描述】:

我遇到了脚本错误。但首先我在做什么。

我正在使我的文本变得丰富多彩,系统应该是这样的。每一秒,新的不同颜色。但是我编写了代码,它显示错误。喜欢:

错误 CS0619: UnityEngine.Component.renderer' is obsolete:Property 渲染器已被弃用。请改用 GetComponent()。 (UnityUpgradable)'

错误 CS1061:类型 UnityEngine.Component' does not contain a definition formaterial' 并且找不到扩展方法 material' of typeUnityEngine.Component'(您是否缺少 using 指令或程序集引用?)

脚本也是这样的。

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;
        }
    }
}

【问题讨论】:

  • error CS0619 清楚地说明了你必须做什么:使用 GetComponent() 而不是渲染器,因为它已被弃用

标签: c# unity3d colors scripting


【解决方案1】:

从 Unity 5 开始,您无法再直接访问 renderer.material.color。必须先使用GetComponent<Renderer>();获取GameObject的组件,然后才能从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;
     }
 }

【讨论】:

  • “文本”游戏对象没有附加“渲染器”。现在该怎么办?
  • MissingComponentException:“文本”游戏对象没有附加“渲染器”,但脚本正在尝试访问它。您可能需要将渲染器添加到游戏对象“文本”。或者您的脚本需要在使用之前检查组件是否已附加。 Colors.Update () (在 Assets/Colors.cs:24)
  • @OneARMINAS 那是因为您附加脚本的对象没有Mesh Renderer。从您附加的位置删除脚本并将其附加到带有Mesh Renderer 的游戏对象。创建一个简单的多维数据集并将脚本附加到它。它应该可以工作,因为立方体有一个Mesh Renderer
  • 这适用于 3d 对象。但是现在如何将此颜色转换脚本放入 UI 文本?
  • @OneARMINAS 此问题已得到解答,您的错误已解决。请为此提出一个新问题并提供链接,我会提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多