Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
hi guys, been stucking around a couple hours, i wanna ask about unity error
ty for anyone that want to answer this


its said that
Quote:
UnityException: RandomRangeInt is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'wall' on game object 'Wall'.
See "Script Serialization" page in the Unity Manual for further details.
UnityEngine.Random.Range (System.Int32 min, System.Int32 max) (at C:/buildslave/unity/build/Runtime/Export/Random/Random.bindings.cs:48)
wall..ctor () (at Assets/Scripts/wall.cs:11)


and this is the code
public class wall : MonoBehaviour
{

    public Vector3 spawnPoint;

    private Transform camPos;
    private int ranXPos = Random.Range(-5, 6);

    void Start()
    {
        transform.position = new Vector3(ranXPos, spawnPoint.y, spawnPoint.z);
        camPos = GameObject.Find("Main Camera").GetComponent<Transform>();
    }


    void Update()
    {
        transform.position += Vector3.back;

        if (transform.position.z < camPos.position.z)
        {
            Destroy(gameObject);
        }
    }
}



EDIT: got new problem where i cant use string
this is the code
<pre><pre>got the problem like that,anyone know why i cant use string?

<pre>    

public class player : MonoBehaviour
{
    public Text distancemoved;
    public float speed;
    float distanceunit = 0;
    public Rigidbody rigid;

    void Start()
    {
................
................
}
    void distance() {
        int distanceunit = 0;
        distanceunit = distanceunit + 1;
        distancemoved = distanceunit.ToString();
    }
}


ty guys
anyone can help?
ty guys

What I have tried:

trying to rewrite here and there but solve nothing. Im very new to the programming
Posted
Updated 22-Jul-19 5:34am
v2

1 solution

Quote:
UnityException: RandomRangeInt is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'wall' on game object 'Wall'.
You are trying to use it in your instance initializer:
C#
private int ranXPos = Random.Range(-5, 6);

So move the initialization to your Start method.
C#
private int ranXPos;

void Start()
{
    ranXPos = Random.Range(-5, 6);
    transform.position = new Vector3(ranXPos, spawnPoint.y, spawnPoint.z);
    camPos = GameObject.Find("Main Camera").GetComponent<Transform>();
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900