Hello,
I’m new to making games. And now i’m trying to create my own 2D game, but I get some errors with my code and i hope that anyone can help me with it. I try to code that if my character jumps, his gun gets hidden. I did a lot of research on how to cumunicate with two scripts so i could get the one script to write a boolean value to the other script, I have been trying all day but i can’t get it to work.
My first script, it makes the character jump and if it jumps it should write a bool value.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController2D controller;
public float runSpeed = 40f;
public Animator animator;
public GameObject my_gun;
gunshow my_gun_script;
bool ShowGun;
float horizontalMove = 0f;
bool jump = false;
bool crouch = false;
// Update is called once per frame
void start()
{
my_gun_script = my_gun.GetComponent<gunshow>(); //Links the gunshow script of the GameObject to my_gun_script
ShowGun = true;
}
void Update()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
animator.SetFloat("Speed", Mathf.Abs(horizontalMove));
if (Input.GetButtonDown("Jump"))
{
jump = true;
animator.SetBool("IsJumping", true); //shows jumping animation
ShowGun = false;
my_gun_script.guns(ShowGun); //ShowGun bool = false, so gun shouldn't be showing
}
if (Input.GetButtonDown("Crouch"))
{
crouch = true;
} else if (Input.GetButtonUp("Crouch"))
{
crouch = false;
}
}
public void OnLanding()
{
animator.SetBool("IsJumping", false);
ShowGun = true;
my_gun_script.guns(ShowGun); //ShowGun bool = true, so gun should be showing
}
public void OnCrouching (bool isCrouching)
{
animator.SetBool("IsCrouching", isCrouching);
}
void FixedUpdate()
{
//move character
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
jump = false;
}
}
My second script, it’s attached to the gameObject and should hide the gun if the character is jumping.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gunshow : MonoBehaviour
{
public void guns(bool ShowGun)
{
if (ShowGun == true)
{
gameObject.SetActive(true); //show gun
}
else if (ShowGun == false)
{
gameObject.SetActive(false); //hide gun
}
}
}
When I save the scripts and look at the console, it doesn’t give any errors.
But when I run the game, everytime I jump or walk it shows this error:
Object reference not set to an instance of an object
And the gun doesn’t hide when I jump.
The gameObject that I use for the gun is called “gun1”.