gpt4 book ai didi

c# - 如何梳理一个RandomRangeInt在Unity中只能从主线程调用?

转载 作者:行者123 更新时间:2023-11-30 20:36:22 26 4
gpt4 key购买 nike

我的目标是让生成的对象具有完全随机的颜色。我一直在问题标题中收到错误消息,我不知道自己在做什么,是对还是错。

using UnityEngine;
using System.Collections;

public class EnemySpawningScript : MonoBehaviour
{
public GameObject spawnType = null;
public float ScaleMin = 0.5f;
public float ScaleMax = 2.0f;
public Color OriginalColorforSpawned = new Color(Random.Range(1,255), Random.Range(1,255), Random.Range(1, 255));

void Awake ()
{
OriginalColorforSpawned = spawnType.GetComponent<Renderer>().sharedMaterial.color;
}

void Update ()
{
if (Input.GetKey (KeyCode.Space))
{
GameObject BasicUnit = Instantiate(spawnType) as GameObject;
BasicUnit.transform.position = this.transform.position;
float ScaleOfEnemies = Random.Range (ScaleMin, ScaleMax);
BasicUnit.transform.localScale = Vector3.one * ScaleOfEnemies;
BasicUnit.AddComponent<Rigidbody>();

BasicUnit.name = "ProtoTypeEnemies";
}
}
}

最佳答案

将颜色初始化放入AwakeStart。您不能在声明行中执行 Random.Range

此外,您尝试在声明它时设置它,但在您的 Awake 中您直接覆盖了它。

编辑:
它应该看起来像这样:

public GameObject spawnType = null;
public float ScaleMin = 0.5f;
public float ScaleMax = 2.0f;
public Color OriginalColorforSpawned;

void Awake ()
{
OriginalColorforSpawned = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f));

spawnType.GetComponent<Renderer>().material.color = OriginalColorforSpawned;
}

编辑:
Color 取值从 0.0f 到 1.0f。

另外,推荐的变量命名是lowerCamelCase(例如originalColorForSpawned)。

编辑:
现在只影响新生成的对象:

using UnityEngine;
using System.Collections;

public class EnemySpawningScript : MonoBehaviour
{
public GameObject spawnType = null;
public float scaleMin = 0.5f;
public float scaleMax = 2.0f;

void Update ()
{
if (Input.GetKey (KeyCode.Space))
{
GameObject basicUnit = Instantiate(spawnType) as GameObject;
basicUnit.transform.position = transform.position;
float scaleOfEnemies = Random.Range (scaleMin, scaleMax);
basicUnit.transform.localScale = Vector3.one * scaleOfEnemies;

// the rigidbody should just be added to the prefab directly
basicUnit.AddComponent<Rigidbody>();

basicUnit.name = "ProtoTypeEnemies";

// change color of this enemy
Color rColor = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f));
basicUnit.GetComponent<Renderer>().material.color = rColor;
}
}
}

关于c# - 如何梳理一个RandomRangeInt在Unity中只能从主线程调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37038154/

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