so, I have two references to game objects. one is the object this script is attached to, myPrefab. the other is a game object with a singleton patter, built to store data between the main game and battle scenes, myBattleManager. I’m trying to make it so that this script will tell the BattleManger what the Object that collided with it is.
the code below works fine in visual studio, but in unity it gives me errors basically saying that I can’t have
GameObject myPrefab;
or
BattleManager myBattleManager = FindObjectOfType();
unless it’s in Awake() or Start().
I’ve tried moving both references and the code from OnCollisionEnter2D() to Awake(), but then it gives me an error on myBattleManager.enemyType = myPrefab; saying that myPrefab hasn’t been defined.
does anyone know how to fix this?
public class Shivee : MonoBehaviour
{
[SerializeField] float moveSpeed;
[SerializeField] float timeBetweenMove;
[SerializeField] float timeBetweenMoveCounter;
[SerializeField] float timeToMove;
[SerializeField] float timeToMoveCounter;
Vector2 moveDirection;
Rigidbody2D myRigidBody;
GameObject myPrefab;
BattleManager myBattleManager = FindObjectOfType<BattleManager>();
bool moving;
// Start is called before the first frame update
void Start()
{
myRigidBody = GetComponent<Rigidbody2D>();
myRigidBody.velocity = Vector2.zero;
timeBetweenMoveCounter = UnityEngine.Random.Range (timeBetweenMove * 0.75f, timeBetweenMove * 1.25f);
timeToMoveCounter = UnityEngine.Random.Range(timeToMove * 0.75f, timeToMove * 1.25f);
}
// Update is called once per frame
void Update()
{
Walk();
}
private void Walk()
{
if (moving)
{
timeToMoveCounter -= Time.deltaTime;
myRigidBody.velocity = moveDirection;
if(timeToMoveCounter < 0f)
{
moving = false;
timeBetweenMoveCounter = timeBetweenMove;
}
} else
{
timeBetweenMoveCounter -= Time.deltaTime;
if(timeBetweenMoveCounter < 0f)
{
moving = true;
timeToMoveCounter = timeToMove;
moveDirection = new Vector2(UnityEngine.Random.Range(-1f, 1f) * moveSpeed,
UnityEngine.Random.Range(-1f, 1f) * moveSpeed);
}
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.name == "player")
{
myBattleManager.enemyType = myPrefab;
Debug.Log("collided");
SceneManager.LoadScene(2);
}
}
}