I am trying to make a random Vector3, but Unity is giving me this error: UnityException: Range is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehavior 'particleMover'. This is my code:
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);
}
}
Vector3 direction = Random.insideUnitSphere;
And you used (1, 360) and it seems you are confusing direction with rotation.
Vector3(x, y, z) - x, y, z are position values, not angles.
In addition, you need to use Time.deltaTime
direction = moveSpeed * direction * Time.deltaTime;
More info: https://docs.unity3d.com/ScriptReference/Time-deltaTime.html
Updated answer:
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With