[英]How to sort out a RandomRangeInt can only be called from the main thread in Unity?
My goal here is to make the spawned object have completely random colors. 我的目标是使生成的对象具有完全随机的颜色。 I keep getting the error in the question title and I have no idea what I'm doing, right or wrong.
我一直在问题标题中得到错误,我不知道我在做什么,对还是错。
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";
}
}
}
Put the color init into Awake
or Start
. 将颜色初始化放入
Awake
或Start
。 You can't do a Random.Range
in the declaration line. 您不能在声明行中执行
Random.Range
。
Also, you try to set it when you declare it, but in your Awake
you override it directly. 另外,您尝试在声明它时进行设置,但是在“
Awake
直接覆盖它。
Edit: 编辑:
It should look like this: 它看起来应该像这样:
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;
}
Edit: 编辑:
Color
takes values from 0.0f to 1.0f. Color
的取值范围是0.0f至1.0f。
Also, the recommended naming for variables is lowerCamelCase
(eg originalColorForSpawned
). 另外,建议的变量命名为
lowerCamelCase
(例如originalColorForSpawned
)。
Edit: 编辑:
Now only effecting the newly spawned object: 现在仅影响新产生的对象:
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.