Hey guys!
My apologies if this question comes up a lot, couldn’t find an answer on my own.
I have a simple problem: I have a game where I create an “food” object, but in a randomized location.
First I’ve managed put this functionality into my GameManager class, which oversees most of the major roles and modules of my program. This version worked without any issues.
Now I am trying to refactor my code, and put the randomization into the food’s own monobehaviour class (which I dubbed “FoodManager”), so you only have to instantiate the prefab, and it itself will take care of the rest. This is where I get into a problem.
Original, working code:
public class GameController : MonoBehaviour
{
public GameObject FoodPrefab;
private void SpawnAFood()
{
Vector3 FoodLocation = new Vector3((Random.Range(-10, 10)),0,(Random.Range(-10, 10)));
Quaternion FoodRotation = new Quaternion(0,0,0,0);
GameObject FoodInstance = Instantiate(FoodPrefab, FoodLocation, FoodRotation);
}
}
New, not working code:
public class GameController : MonoBehaviour
{
public GameObject FoodPrefab;
private void SpawnAFood()
{
GameObject FoodInstance = Instantiate(FoodPrefab);
FoodInstance.GetComponent<FoodManager>().Relocate(); //second attempt to call this function
}
}
And this is attached to the FoodPrefab:
public class FoodManager : MonoBehaviour {
// Use this for initialization
void Start () {
//Relocate(); //original attempt to call this function, didn't work
}
public void Relocate ()
{
GetComponent<Rigidbody>().position = new Vector3((Random.Range(-10, 10)), 0, (Random.Range(-10, 10)));
}
// Update is called once per frame
void Update () {
}
}
In the not working code I’ve tried to first put the Relocate() into the Start() of FoodManager, so that the GameManager won’t have to call that one. That did not work, so I’ve started to experiment.
Thanks for the replies and help in advance!