Неправильный тег при столкновении № 2 - PullRequest
0 голосов
/ 03 апреля 2020

Здравствуйте, я делаю 2D-игру, и у меня есть игрок, который должен столкнуться с 2 объектами. Первый объект дает ему больше здоровья и имеет тег «power up» и работает, но второй, который имеет тег «Hurt», не работает. Что я должен изменить в сценарии? Здесь это скрипт для «PowerUp», а здесь это скрипт плеера.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class PowerUpDetector : MonoBehaviourPun
{
    // reference this via the Inspector
    [SerializeField] private Character healthbar;
    [SerializeField] private Character health;
   

    private void Awake()
    {
        if (!healthbar) healthbar = GetComponent<Character>();
        
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        // or whatever tag your powerups have
        if (!other.CompareTag("PowerUp"))
        {
            Debug.LogWarning($"Registered a collision but with wrong tag: {other.tag}", this);
            return;
        }
        
        var powerup = other.GetComponent<PowerUp>();
        if (!powerup)
        {
            Debug.LogError($"Object {other.name} is tagged PowerUp but has no PowerUp component attached", this);
            return;
        }

        Debug.Log("Found powerup, pick it up!", this);
        powerup.Pickup(healthbar);
        if (!other.CompareTag("Hurt"))
        {
            if (photonView.IsMine)
            {
                photonView.RPC("Damage", RpcTarget.All);
                
            }

            
        }



    }
    [PunRPC]
    void Damage()
    {
        health -= 20;
    }

}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using Photon.Pun;
using Photon.Realtime;
using Photon;
using UnityEngine.UI;


public class Character : MonoBehaviourPun,IPunObservable
{

    Rigidbody2D rb;
    float dirX;

    [SerializeField]
    float moveSpeed = 5f, jumpForce = 400f, bulletSpeed = 500f;

    [SerializeField] private float health = 100;
    [SerializeField] private Slider slider;
    [SerializeField] private Gradient gradient;
    [SerializeField] private Image fill;

    Vector3 localScale;
   
    public Transform barrel;
    public Rigidbody2D bullet;

    // Use this for initialization
    void Start()
    {
        localScale = transform.localScale;
        rb = GetComponent<Rigidbody2D>();
        if (photonView.IsMine)
        {
            
            
        }
        else
        {

        }
    }
    public float Health
    {
        get { return health; }
        set
        {
            health = value;
            slider.value = health;
            fill.color = gradient.Evaluate(slider.normalizedValue);
        }
    }

    private void OnCollisionEntered2D(Collision2D col)
    {
        if( col.gameObject.CompareTag ("Hurt"))
        {
            if (photonView.IsMine)
            {
                photonView.RPC("Damage", RpcTarget.All);
            }
        }
    }
    [PunRPC]
    void Damage()
    {
        health -= 20;
    }
    // Update is called once per frame
    void Update()
    {
        if (photonView.IsMine)
        {
            dirX = CrossPlatformInputManager.GetAxis("Horizontal");
            if (dirX != 0)
            {
                barrel.up = Vector3.right * Mathf.Sign(dirX);
            }

            if (CrossPlatformInputManager.GetButtonDown("Jump"))
                Jump();

            if (CrossPlatformInputManager.GetButtonDown("Fire1"))
                Fire();
            
        }
        else
        {

        }
    }

    void FixedUpdate()
    {
        if (photonView.IsMine)
        {
            rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
        }
    }




    void Jump()
    {
        if (photonView.IsMine)
        {
            if (rb.velocity.y == 0)
                rb.AddForce(Vector2.up * jumpForce);
        }
    }

    void Fire()
    {
        if (photonView.IsMine)
        {
            var firedBullet = Instantiate(bullet, barrel.position, barrel.rotation);
            firedBullet.AddForce(barrel.up * bulletSpeed);
        }
    }

    public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.IsWriting)
        {
            stream.SendNext(health);
        }else if (stream.IsReading)
        {
           health = (float)stream.ReceiveNext();
        }
    }
    public void SetMaxHealth(int value)
    {
        if (photonView.IsMine)
        {
            slider.maxValue = value;
            // The property handles the rest anyway
            Health = value;
        }

    }
}

У меня ошибка в «Детекторе включения питания» при работоспособности - = 20 (оператор - = не может быть применен) к операндам типа «Символ» и «int "

1 Ответ

0 голосов
/ 03 апреля 2020

Я думаю, вам придется использовать health.Health. Ваша переменная health относится к классу Character. Поскольку вы хотите изменить состояние здоровья, вам придется использовать вместо этого свойство этого класса. Поэтому попробуйте:

health.Health -= 20;

Я бы порекомендовал переименовать переменную health во что-то еще, связанное с классом Character.

...