D
D
Digital172021-03-23 23:36:28
C++ / C#
Digital17, 2021-03-23 23:36:28

Unity not responding to script?

I have the written code, and it is correct, because for the sake of checking what is the error: in the code or Unity, exactly the working code was copied using hotkeys. The problem is this: after the lines with GetComponentInChildren, it should display access to the parameters (speed, jump strength) in the unit itself in the Hero tab? But for some reason it doesn't.

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

public class Hero : MonoBehaviour
{
    private int lives = 3;
    private float speed = 4.0f;
    private float jumpforce = 1.0f;
    public Rigidbody2D PlayerRigidbody;
    public Animator charAnimator;
    public SpriteRenderer sprite;
    bool OnGround;
    private void Awake()
    {
        PlayerRigidbody = GetComponentInChildren<Rigidbody2D>();
        charAnimator = GetComponentInChildren<Animator>();
        sprite = GetComponentInChildren<SpriteRenderer>();
    }
    void Start()
    {
        
    }

    void Move()
    {
        Vector3 tempvector = Vector3.right * Input.GetAxis("Horizontal");
        transform.position = Vector3.MoveTowards(transform.position, transform.position + tempvector, speed * Time.deltaTime);
        if (tempvector.x < 0)
        {
            sprite.flipX = true;
        }
        else
        {
            sprite.flipX = false;
        }

    }
    void jump()
    {
        PlayerRigidbody.AddForce(transform.up * jumpforce, ForceMode2D.Impulse);
    }
    void CheckGround()
    {
        Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, 2f);
        OnGround = colliders.Length > 1;
        Debug.Log(colliders.Length);
    }

    private void FixedUpdate()
    {
        CheckGround();
    }
    void Update()
    {
        if (Input.GetButton("Horizontal"))
        {
            Move();
        }
        if (OnGround && Input.GetButton("Jump"))
        {
            jump();
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
namee, 2021-03-24
@Digital17

Read the documentation in such cases
https://docs.unity3d.com/ScriptReference/Component...
Perhaps the component is not active.
In this case, it is better to use
https://docs.unity3d.com/ScriptReference/Component...
But perhaps the reason is that there is no such component in the descendants.
Perhaps all these components hang on the current object, and you are looking in the descendants.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question