Can't get to work a non behaviour constructor with random generated variables
public class Ship
{
public int ShipType;
public int ShipLvL;
public int Health;
public int ShipPosition;
public int GetPosition()
{
ShipPosition = Random.Range(1, 9);
return ShipPosition;
}
public Ship()
{
ShipType = Random.Range (1, 3);
Debug.Log("Type: " + ShipType);
ShipLvL = Random.Range(1, 10);
Debug.Log("LVL: " + ShipLvL);
Health = ShipLvL * ShipType * 500;
Debug.Log("Health: " + Health);
}
public int GetH()
{
return Health;
}
public int GetL()
{
return ShipLvL;
}
public int GetT()
{
return ShipType;
}
}
I have created this Class. As you can see 2 variables are generated Randomly. When i create an object of this class in another script it gets me an error when i run the game: "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 'Stats' on game object ')'."
This is the declaration of the Object:
public class Stats : MonoBehaviour {
public Ship MyShip = new Ship();
public int Health;
public int LvL, Type;
// Use this for initialization
void Start () {
Health = MyShip.GetH();
LvL = MyShip.GetL();
Type = MyShip.GetT();
}
If i doubleclick the error it highlights this lines:
1. ShipType = Random.Range (1, 3);
2. ShipLvL = Random.Range(1, 10);
3. Health = ShipLvL * ShipType * 500;
What's the problem?
Answer by MacDx · May 14, 2018 at 04:11 PM
The problem is exactly what the message says. Specifically this part:
RandomRangeInt is not allowed to be called from a MonoBehaviour constructor (or instance field initializer)
You cannot use Random Range in an instance field initializer. So this line is where the error starts.
public Ship MyShip = new Ship();
So, instead of calling new Ship(), on your field declaration, you should be calling it inside of Start like this:
public Ship MyShip;
void Start(){
MyShip = new Ship();
Health = MyShip.GetH();
LvL = MyShip.GetL();
Type = MyShip.GetT();
}
Hope this helps!
Your answer
![](https://koobas.hobune.stream/wayback/20220612162637im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
C# Find specific object by getting one of its variables 0 Answers
Adding classes to objects 0 Answers
2D - Object follow cursor on X-axis. 0 Answers
add 3d text through script on a object 1 Answer
Falling object respawner 1 Answer