I have 2 scripts, PlayerScript and PlayerVehicleScript. Both are C#.
The PlayerScript is enabled and the PlayerVehicleScript is disabled.
In my PlayerScript I have programmed it so when you are within a certain distance from the vehicle, you can enter the car when you press Q.
PlayerScript:
if (Input.GetKeyDown(KeyCode.Q))
{
if(Vector3.Distance(transform.position, PlayerVehicle.transform.position) < 25)
{
//Turn main camera off
MainCamera.gameObject.active = false;
//Turn car camera on
CarCamera.gameObject.active = true;
//Enables vehicle script so player can drive car
GetComponent<PlayerVehicleScript>().enabled = true;
//Disables the player script including player controls
GetComponent<PlayerScript>().enabled = false;
}
}
And in my PlayerVehicleScript I have disabled the script by using
[RequireComponent (typeof(PlayerVehicleScript))]
[RequireComponent (typeof(PlayerScript))]
public class YourClassName : MonoBehaviour {
private Transform thisTransform;
private PlayerVehicleScript playerVehicleScript;
private PlayerScript playerScript;
void Awake()
{
thisTransform = GetComponent<Transform>();
playerScript = GetComponent<PlayerScript>();
playerVehicleScript = GetComponent<PlayerVehicleScript>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Q))
{
if( (thisTransform.position - PlayerVehicle.transform.position).sqrMagnitude < 625)
{
//Turn main camera off
MainCamera.gameObject.active = false;
//Turn car camera on
CarCamera.gameObject.active = true;
//Enables vehicle script so player can drive car
playerVehicleScript.enabled = true;
//Disables the player script including player controls
playerScript.enabled = false;
}
}
}
}
Not tested, but should work. Basically it requires (RequireComponent before your class name) and cache components on Awake(). Vector3.Distance was replaced by sqrMagnitude, which is faster, but decide yourself what works better on your project, sometimes an approach with sqrMagnitude is enough (and faster than Vector3.Distance()).
NOTE: make sure PlayerVehicle.transform.position returns the correct value, I don’t know what is this class on your project and how you identify a near vehicle.
Giving your first post I assume you attach these scripts to this component (as you’re using GetComponent on the same script, no GameObject.Find or similar), but probably you are trying to get this scripts on another component, so you need to find this component first with GameObject.Find(“name of gameobject”).GetComponent().
You don’t provide enough information to solve this issue. Anyway, if you remove and attach the script I provided should work because will attach automatically the required scripts (If you don’t do you will need to attach these scripts manually), but I’m not sure about your implementation and their correspondence with gameobjects and scripts.
The PlayerScript is attached to the Player and the PlayerVehicleScript is attached to the PlayerVehicle.
I am using your code but still get that same error and I have no idea why