So, I want to generate a random speed and rotation value for the game that I'm (trying) to make, but if I generate the values in the Update function, it will keep generating new values every frame, but if I generate the values in the Start function, the Update function doesn't recognize it: This is the script I have now (which doesn't work):
void Start()
{
float randomRotation = Random.Range(0, 360f);
float randomSpeed = Random.Range(1f, 5f);
}
void Update()
{
transform.rotation = Quaternion.Euler(0, 0, randomRotation);
Vector3 pos = transform.position;
Vector3 velocity = new Vector3(0, randomSpeed, 0);
pos += transform.rotation * velocity;
transform.position = pos;
}
The problem here is that the Update void does not know what randomRotation means, so it cannot do anything, however if I try public float randomRotation
it looks like the whole script gets confused and I get a compiler error: error CS1022: Type or namespace definition, or end-of-file expected
Does anyone know how to fix this?
Thanks!
You have to define the randomSeed
(and randomRotation
) variable outside of the start function like so:
float randomRotation = 0.0f;
float randomSpeed = 0.0f;
void Start()
{
randomRotation = Random.Range(0, 360f);
randomSpeed = Random.Range(1f, 5f);
}
void Update()
{
transform.rotation = Quaternion.Euler(0, 0, randomRotation);
Vector3 pos = transform.position;
Vector3 velocity = new Vector3(0, randomSpeed, 0);
pos += transform.rotation * velocity;
transform.position = pos;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.