преобразование не завершается в текущем контексте - PullRequest
0 голосов
/ 18 ноября 2018

Мне трудно понять, почему мое преобразование неверно.Может ли кто-нибудь помочь мне в этой проблеме.Я пытаюсь сделать ФСМ для своего врага, чтобы он либо шел на игрока, либо на еду.Но когда я пытаюсь проверить это, я получаю сообщение об ошибке компилятора.

using UnityEngine;
using System.Collections;

public class Enemy : MovingObject 
{
    public int playerDamage;

    private Animator animator;
    private Transform target;
    private bool skipMove;
    private Transform Player;
    public AudioClip enemyAttack1;
    public AudioClip enemyAttack2;

    protected override void Start () 
    {
        GameManager.instance.AddEnemeyToList(this);
        animator = GetComponent<Animator> ();
        target = GameObject.FindGameObjectWithTag ("Food").transform;
        base.Start ();

        AIEnemy();
        Player = GameObject.FindWithTag("Player").transform;
    }

    protected override void AttemptMove<T> (int xDir, int yDir) 
    {
        if (skipMove) 
        {
            skipMove = false;
            return;
        }

        base.AttemptMove <T> (xDir, yDir);

        skipMove = true;
    }

    public void MoveEnemy() 
    {
        int xDir = 0;
        int yDir = 0;

        if (Mathf.Abs (target.position.x - transform.position.x) < float.Epsilon)
            yDir = target.position.y > transform.position.y ? 1 : -1;
        else
            xDir = target.position.x > transform.position.x ? 1 : -1;

        AttemptMove<Player> (xDir, yDir);
    }

    protected override void OnCantMove <T> (T component) 
    {
        Player hitPlayer = component as Player;
        hitPlayer.LoseFood (playerDamage);
        animator.SetTrigger("enemyAttack");
        SoundManager.instance.RandomizeSfx (enemyAttack1, enemyAttack2);
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Food")
        {
            other.gameObject.SetActive(false);
        }
        else if (other.tag == "Soda")
        {
            other.gameObject.SetActive(false);
        }
    }

    void AIEnemy()
    {
        int State = 0;

        if (State == 0)
        {
            transform.LookAt(Player);
            State++;
        }

        if (State == 1)
            transform.LookAt(target);

        Debug.Log("State 1");
        State++;

        if (State == 2)
        {
            Debug.Log("State 2");
        }

    }

}

public Transform FindClosetFood()
{
    float minDistance = float.PositiveInfinity;
    Transform closetFood = null;
    GameObject[] foods = GameObject.FindGameObjectsWithTag("Food");
    for(int i = 0; i<foods.Length; i++)
    {
        float distance = Vector2.Distance(transform.position, foods[i].transform.position);
        if (distance < minDistance)
        {
            minDistance = distance;
            closetFood = foods[i].transform;
        }
    }
    return closetFood;
 }

}

Я добавил приватный Transform Player.Так что мой враг знает, на что смотреть, но я все еще ничего не вижу в консолиИ я попытался назвать это в начале.Но теперь я закончил с этой ошибкой компилятора.

Ошибка появляется в этой строке

float distance = Vector2.Distance("transform".position, foods[i].transform.position);

Скрипт MovingObject:

using UnityEngine;
using System.Collections;

public abstract class MovingObject : MonoBehaviour 
{
    public float moveTime = 0.1f;
    public LayerMask blockingLayer;

    private BoxCollider2D boxCollider;
    private Rigidbody2D rb2D;
    private float inverseMoveTime;

    // Use this for initialization
    protected virtual void Start () 
    {
        boxCollider = GetComponent<BoxCollider2D> ();
        rb2D = GetComponent<Rigidbody2D> ();
        inverseMoveTime = 1f / moveTime;
    }

    protected bool Move (int xDir, int yDir, out RaycastHit2D hit) 
    {
        Vector2 start = transform.position;
        Vector2 end = start + new Vector2 (xDir, yDir);

        boxCollider.enabled = false;
        hit = Physics2D.Linecast (start, end, blockingLayer);
        boxCollider.enabled = true;

        if (hit.transform == null) 
        {
            StartCoroutine(SmoothMovement (end));
            return true;
        }

        return false;
    }

    protected IEnumerator SmoothMovement (Vector3 end) 
    {
        float sqrRemainingDistance = (transform.position - end).sqrMagnitude;
        while (sqrRemainingDistance > float.Epsilon) 
        {
            Vector3 newPosition = Vector3.MoveTowards (rb2D.position, end, inverseMoveTime * Time.deltaTime);
            rb2D.MovePosition(newPosition);
            sqrRemainingDistance = (transform.position - end).sqrMagnitude;
            yield return null;
        }
    }

    protected virtual void AttemptMove <T> (int xDir, int yDir) where T : Component
    {
        RaycastHit2D hit;
        bool canMove = Move (xDir, yDir, out hit);

        if (hit.transform == null)
            return;

        T hitComponent = hit.transform.GetComponent<T> ();

        if(!canMove && hitComponent != null)
            OnCantMove (hitComponent);
    }

    protected abstract void OnCantMove <T> (T component) where T : Component;
}

1 Ответ

0 голосов
/ 18 ноября 2018

Не может найти transform.position, потому что преобразование - это переменная, необъявленная в компоненте. MonoBehaviour диски из Behaviour и Behaviour получены из Component. Чтобы получить доступ к переменной transform, ваш сценарий должен быть производным от одного из них. Хотя MonoBehaviour - это то, из чего должен исходить сценарий.

В коде ваш скрипт Enemy уже получен из скрипта MovingObject, который происходит от MonoBehaviour, так что он должен дать вам доступ к переменной transform, но есть проблема. В вашем скрипте Enemy есть дополнительный } в конце функции AIEnemy(). Этот дополнительный } в конце функции AIEnemy() закрывает или отмечает конец * 1020 Поэтому скрипт * делает переменную transform недоступной для вас. Удалите лишние } в конце функции AIEnemy(), и ваша проблема должна быть исправлена.

Если вы не можете его найти, используйте новый скрипт Enemy ниже:

public class Enemy : MovingObject
{

    public int playerDamage;

    private Animator animator;
    private Transform target;
    private bool skipMove;
    private Transform Player;
    public AudioClip enemyAttack1;
    public AudioClip enemyAttack2;

    protected override void Start()
    {
        GameManager.instance.AddEnemeyToList(this);
        animator = GetComponent<Animator>();
        target = GameObject.FindGameObjectWithTag("Food").transform;
        base.Start();

        AIEnemy();
        Player = GameObject.FindWithTag("Player").transform;


    }

    protected override void AttemptMove<T>(int xDir, int yDir)
    {
        if (skipMove)
        {
            skipMove = false;
            return;
        }

        base.AttemptMove<T>(xDir, yDir);

        skipMove = true;
    }

    public void MoveEnemy()
    {
        int xDir = 0;
        int yDir = 0;

        if (Mathf.Abs(target.position.x - transform.position.x) < float.Epsilon)
            yDir = target.position.y > transform.position.y ? 1 : -1;
        else
            xDir = target.position.x > transform.position.x ? 1 : -1;

        AttemptMove<Player>(xDir, yDir);
    }

    protected override void OnCantMove<T>(T component)
    {
        Player hitPlayer = component as Player;
        hitPlayer.LoseFood(playerDamage);
        animator.SetTrigger("enemyAttack");
        SoundManager.instance.RandomizeSfx(enemyAttack1, enemyAttack2);
    }

    private void OnTriggerEnter2D(Collider2D other)
    {

        if (other.tag == "Food")
        {

            other.gameObject.SetActive(false);
        }
        else if (other.tag == "Soda")
        {

            other.gameObject.SetActive(false);
        }


    }

    void AIEnemy()
    {
        int State = 0;

        if (State == 0)
        {
            transform.LookAt(Player);
            State++;
        }
        if (State == 1)

            transform.LookAt(target);
        Debug.Log("State 1");
        State++;
        if (State == 2)
        {
            Debug.Log("State 2");
        }

    }


    public Transform FindClosetFood()
    {
        float minDistance = float.PositiveInfinity;
        Transform closetFood = null;
        GameObject[] foods = GameObject.FindGameObjectsWithTag("Food");
        for (int i = 0; i < foods.Length; i++)
        {
            float distance = Vector2.Distance(transform.position, foods[i].transform.position);
            if (distance < minDistance)
            {
                minDistance = distance;
                closetFood = foods[i].transform;
            }
        }
        return closetFood;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...