尝试在 Unity 中创建随机 Vector3

Spa*_*909 4 c# unity-game-engine

我试图制作一个随机的 Vector3,但 Unity 给了我这个错误: UnityException: Range is not allowed to be called from a MonoBehaviour constructor (or instance fieldinitializer), call it in Awake or Start 相反。从 MonoBehavior 中调用“articleMover”。这是我的代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

Vector3 direction = Random.insideUnitSphere;
Run Code Online (Sandbox Code Playgroud)

你使用了 (1, 360) ,看来你混淆了方向和旋转。

Vector3(x, y, z) - x, y, z 是位置值,而不是角度。

此外,您还需要使用Time.deltaTime

direction = moveSpeed * direction * Time.deltaTime;
Run Code Online (Sandbox Code Playgroud)

更多信息: https: //docs.unity3d.com/ScriptReference/Time-deltaTime.html

更新的答案:

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;
    private Vector3 direction = Vector3.zero;

    void Start()
    {
        direction = Random.insideUnitSphere;
    }

    void Update()
    {
        rf.position += direction * moveSpeed * Time.deltaTime;
        // If this script is attached to tf object
        // transform.position += direction * moveSpeed * Time.deltaTime;
    }
}
Run Code Online (Sandbox Code Playgroud)