-2

Здраствуйте, я делаю игру, и хочу сделать так что бы песонаж прыгал при нажатии на кнопку. Но у меня в коде вылазит ошибка. Но я не понимаю что не так, вот код для персонажа и код для кнопки

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

public class HeroMove : MonoBehaviour { public float horisontalSpeed; float speed;

Rigidbody2D rb;
private bool isGrounded = false;
public int jumpforce;
private JumpButton JumpButtonScript;
private GameObject Button;

// Start is called before the first frame update
void Start()
{
    rb = GetComponent<Rigidbody2D>();
    Button = GameObject.Find("Button");

}

// Update is called once per frame
void FixedUpdate()
{
    if(Input.GetKey(KeyCode.A)){
        speed = -horisontalSpeed;
    } else if(Input.GetKey(KeyCode.D)){
         speed = horisontalSpeed;
    }

}
void Update()
{

 Jump();

}
private void Jump()
{
    GameObject.Find("Button").GetComponent<JumpButton>();

    if(JumpButtonScript.isPressed && !isGrounded)
 {
 gameObject.GetComponent<Rigidbody2D>().AddForce(Vector3.up * jumpforce);
 JumpButtonScript.isPressed = false;
 isGrounded = false;
 JumpButtonScript.gameObject.SetActive(false);
 } else if (!isGrounded) 
 {
  JumpButtonScript.gameObject.SetActive(true);
 }



}

}

Код для кнопки :

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class JumpButton : MonoBehaviour, IPointerClickHandler { public bool isPressed = false; public void OnPointerClick(PointerEventData eventData) { isPressed = true; } }

2 Answers2

1
GameObject.Find("Button").GetComponent<JumpButton>()

Скорее это просто лишний код. Более правильный вариант будет:

JumpButtonScript = Button.GetComponent<JumpButton>()

Сама ошибка возникает из-за попытки взаимодействия с переменной без присвоенного значения:

JumpButtonScript.isPressed = false;
Lesh
  • 96
  • 4
0

Думаю должно быть так:

JumpButtonScript = GameObject.Find("Button").GetComponent<JumpButton>();

if(JumpButtonScript.isPressed && !isGrounded) ... // .......

То есть компонент-то нашли через GetComponent, а вот сложить её никуда не сложили. Поэтому JumpButtonScript.isPressed выдаёт ошибки, потому что JumpButtonScript не определён.