it’s giving me this error
error CS0103: The name 'player_instance' does not exist in the current context
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public GameObject Ground;
public GameObject Player;
public Camera PlayerCamera;
public Vector3 CameraOffset;
public float MovementForce = 4000f;
void Start()
{
Instantiate(Ground, new Vector3(0, 0, 0), Quaternion.identity);
Instantiate(Player, new Vector3(0, 1, 0), Quaternion.identity);
player_instance = Player.GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow))
{
player_instance.Rigidbody.AddForce(-MovementForce * Time.deltaTime, 0, 0);
Player.GetComponent<Rigidbody>().AddForce(-MovementForce * Time.deltaTime, 0, 0);
}
else if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow))
{
// self_rigidbody.AddForce(-MovementForce * Time.deltaTime, 0, 0);
}
}
}
When you try to set the player_instance
variable equal to Player.GetComponent<Rigidbody>()
, you are trying to access the RigidBody
of the prefab object saved in the assets file, instead of the RigidBody
of the object you just instantiated that is actually in the scene.
You can fix this by having
player_instance = Instantiate(everything you put here).GetComponent<Rigidbody>();
This will still instantiate your game object while allowing you to save it to a variable in the same line of code. This ends with GetComponent
because I am assuming that player_instance
is a RigidBody
variable, if it’s just a GameObject
variable then that last part isn’t necessary.
Another thing to do is to declare player_instance
as a variable at the top of your script, which you may have already done, but is not shown in the code you shared.
The last thing I would say is to do a null check in your update function so that you never get an error if the object fails to instantiate or gets destroyed later on.
You can do this be putting this in update
If(player_instance != null)
{
//your input code
}
Or this before all of your code if you do not like having too much depth/indented layers. (I don’t do this personally but I’m still a beginner in a way).
If(player_instance == null)
{
Debug.LogWarning(); //this is optional
continue;
}
Hope this helps