我正在尝试创建一个随机的Vector3,但Unity给了我这个错误:UnityException:Range不允许从MonoBehaviour构造函数(或实例字段初始化器)调用,应该在Awake或Start中调用。来自MonoBehavior 'particleMover'的调用。
以下是我的代码:
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using UnityEngine;
public class particleMover : MonoBehaviour
{
public float moveSpeed;
public float temperature;
public Rigidbody rb;
public Transform tf;
static private float[] directions;
// Start is called before the first frame
void Start()
{
System.Random rnd = new System.Random();
float[] directions = { rnd.Next(1, 360), rnd.Next(1, 360), rnd.Next(1, 360) };
}
// Update is called once per frame
void Update()
{
Vector3 direction = new Vector3(directions[0], directions[1], directions[2]);
direction = moveSpeed * direction;
rb.MovePosition(rb.position + direction);
}
}
direction = Random.insideUnitSphere
doesn't necessarily return a normalized direction vector. It is inside a unit sphere, not on its surface. So you should rather dodirection = Random.insideUnitSphere.normalized;
- derHugo