I’m making a game with two controllable characters. The characters are both in the same area and when I press a button, I want the player to take control of the other character and leave the other where it was left. I have both characters as separate objects with their own controller script but I have trouble getting them work as I want to.
What I’ve been trying to do is has CharacterController1 enabled at the start of the game and when I press Q, the CC1 disables and CC2 enables. My CC1 to CC2 switch looks like this:
public CharacterController1 ascript;
public CharacterController2 bscript;
void Start () {
ascript = GetComponent<CharacterController1> ();
bscript = GetComponent<CharacterController2> ();
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.Q))
{
ascript.enabled = !ascript.enabled;
bscript.enabled = bscript.enabled;
}
}
The CC2 has a similar script but the Update part is the opposite way. The problem I run to is that when I press play both of my CCs are enabled and so I control both character. When I press Q CC1 disables like it should but I can’t get the CC2 to disable when I only want to control Character1.
I’ve tried adding lines like:
if (ascript.enabled)
{
bscript.enabled = !bscript.enabled;
}
or
void Start() {
bscript.enabled = !bscript.enabled;
}
To the CC2 script but I can’t get it to work.
Also I keep getting this Error message:
NullReferenceException: Object reference not set to an instance of an object.
I have dragged the scripts to the inspector spaces made by the public CC1 and public CC2 and didn’t have a problem there but when I press play and looks at Character1 for example the CC2 has disappeared from there. I have never done coding before and I have been googling and trying different things for hours but can’t figure out what I’m doing wrong.
you need to include the complete error message and the script it references (unless it's really long) so we can see exactly which line produces the error. for reference,
– gjfGetComponentwill get the component from the currentGameObject. if you want to get it from a different object, you'll need to be more explicit. something like: someOtherComponentReference = someOtherObject.GetComponent<SomeOtherComponent>(); if you're new to coding, i'd suggest going through some of the unity tutorials until you get the hang of things.