Cant Disable Script on Another Gameobject
Hello, i have been looking through google but nothing works, help please
i have car gameobject in hierarchy and it has Vehicle Controler.cs Standard Inputs.cs and Reset Car.cs components attached.
i made another gameobject and put as child of car gameobject.
i want to disable and enable Vehicle Controler.cs Standard Inputs.cs this guys but cant.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnterCar : MonoBehaviour
{
public GameObject CarCam;
public GameObject ThePlayer;
public GameObject TheCar;
public int TriggerCheck;
public void OnTriggerEnter(Collider other)
{
TriggerCheck = 1;
}
public void OnTriggerExit(Collider other)
{
TriggerCheck = 0;
}
public void Update()
{
if (TriggerCheck == 1)
{
if (Input.GetButtonDown("Action"))
{
CarCam.SetActive(true);
ThePlayer.SetActive(false);
TheCar.GetComponent<VehicleController>().enabled = true; //not work
TheCar.GetComponent(VehiclePhysics).enabled = true; //not work
TheCar.GetComponent("VehiclePhysics").enabled = true; //not work
}
}
}
}
Answer by A_Sad_Shoe · Mar 29, 2020 at 01:21 PM
You seem to be missing a reference to both VehicleController and VehiclePhysics, if you're using visual studio you can simply tap alt+enter while highlighting the class name and it will pop up with the path. As to why each one doesn't work:
TheCar.GetComponent<VehicleController>().enabled = true; //not work
The reason you can't access 'enabled' is because of the missing references, as the script can't see if the component you're trying to access 'enabled' on derives from MonoBehaviour, add a reference to VehicleController and you should be good.
TheCar.GetComponent(VehiclePhysics).enabled = true;
this will not work since you're trying to use the typename as the actual type try to use TheCar.GetComponent(typeof(VehiclePhysics)).enabled = true;
instead.
TheCar.GetComponent("VehiclePhysics").enabled = true; //not work
You should never do this unless forced to, as the syntax using the type is preferred, but if you are forced to do this, try casting it to the type you want (TheCar.GetComponent("VehiclePhysics") as VehiclePhysics).enabled = true;
or ((VehiclePhysics)TheCar.GetComponent("VehiclePhysics")).enabled = true;
Hope that helps a bit.