RandomRange in void update

Hello, ist it possible to put randomrange in void update() im trying to obtain a new random value everytime an event happens, but its only letting me put Random.Range in void (start) , thank you! Code:

using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.VisualScripting;
using UnityEngine;

public class CharacterCtrl : MonoBehaviour
{
    public int Speed;
    public int JumpForce;
    public GameObject Character;
    public GameObject Coin;
    public Rigidbody2D rb2D;
    public float Countdown = 3f;
    public float Coinx = Random.Range(10f, 100f);
    public float Coiny = Random.Range(10f, 100f);
    // Start is called before the first frame update
    void Start()
    {
        rb2D.Sleep();
    }

    // Update is called once per frame
    void Update()
    {
       
        void Timer ()
        {
            Countdown = Countdown - Time.deltaTime;
        }

        Timer();

        if (Countdown <= 0)
        {
            rb2D.WakeUp();
        }
        if (Input.GetKeyDown(KeyCode.A) && Countdown <= 0 || Input.GetKeyDown(KeyCode.LeftArrow)&& Countdown <= 0)
        {
            rb2D.velocity = Vector2.left * Speed;
        }

        if (Input.GetKeyDown(KeyCode.D) && Countdown <= 0 || Input.GetKeyDown(KeyCode.RightArrow) && Countdown <= 0)
        {
            rb2D.velocity = Vector2.right * Speed;
        }

        if (Input.GetKeyDown(KeyCode.Space) && Countdown <= 0)
        {
            rb2D.velocity = Vector2.up * JumpForce;
        }

    }

    void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.gameObject == Coin)
        {
            Instantiate(Coin, new Vector2(Coinx,Coiny), transform.rotation);
        }
    }
}

Error message: 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 MonoBehaviour ‘CharacterCtrl’.

Editor version: Unity 2022.3.8f1; Direct X version 11

This has nothing to do with Update()
You can NOT call Random.Range when declaring a value. You need to declare it and then fill the value with Random.Range in Start((

1 Like

Keep the declaration at the top, without setting a value.

Set a value, using Random.Range, in your if (collider.gameObject == Coin)
loop. I assume you want to initiate every coin at a random spot.

Worth noting that if you do actually need a random value when declaring the field, you can use new System.Random() instead.

1 Like