gpt4 book ai didi

c# - 从 Assets 中获取 Material

转载 作者:行者123 更新时间:2023-12-03 21:40:49 24 4
gpt4 key购买 nike

在我的 Unity 项目中,我尝试使用一些自制 Material 来突出显示某些对象。不幸的是,我找到的代码不起作用。

以下脚本被添加到三个不同的游戏对象中:

Renderer[] rend_ThisObject;
Material white, red;

void Start()
{
// I tried the following two code parts:
white = Resources.Load<Material>("White");
white = Resources.Load("Material/White.mat", typeof(Material)) as Material;

red = Resources.Load<Material>("Red");
red = Resources.Load("Material/Red.mat", typeof(Material)) as Material;
}

void Update()
{
foreach (var child in rend_ThisObject)
{
child.material = blinkObject ? white : red;
}
}

如果我运行该项目,带有脚本的游戏对象会显示为粉红色并且不会闪烁。

如果我将 Material white, red; 更改为 public Material white, red; 它工作正常。我必须更改什么才能从我的 Assets /资源/ Material 文件夹中获取 Material ?

最佳答案

一般来说:

来自Unity自己的Best practise for Resources :

Don't use it.

简单地使用您的 public 字段并通过 Inspector 设置它们有什么问题?

如果您不希望它们是public 则只需使用[SerializeField]

[SerializeField] private Material white;
[SerializeField] private Material red;

而是通过 Inspector 分配它们!


然后假设您的路径不是assets/resources/material 而是Assets/Resources/Material 参见Resources.Load !

你试过了

white = Resources.Load<Material>("White");
white = Resources.Load("Material/White.mat", typeof(Material)) as Material;

两者都是错误的:

  • 第一次缺少文件夹路径

    The path is relative to any folder named Resources inside the Assets folder of your project

  • 第二个文件结尾太多。

    Note: Extensions must be omitted.

所以加载路径文件

Assets/Resources/Material/White.mat

应该是

white = Resources.Load<Material>("Material/White");

现在是另一个一般说明:

每帧的基础上进行这种闪烁不是一个好主意!

而是使用某种延迟,例如

// adjust via the Inspector as well
[Tooltip("Color changes per second")]
[SerializeField] private float blinkFrequency = 2f;

private float timer;

void Update()
{
timer -= Time.deltaTime;
if(timer <= 0)
{
timer = 1 / blinkFrequency;

blinkObject = !blinkObject;
foreach (var child in rend_ThisObject)
{
child.material = blinkObject ? white : red;
}
}
}

关于c# - 从 Assets 中获取 Material ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60389773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com