MissingComponentException: к объекту игры «Balletjes (Clone)» не прикреплен «SpriteRenderer», но сценарий пытается получить к нему доступ - PullRequest
0 голосов
/ 09 января 2019

Я получаю эту ошибку:

«MissingComponentException: к игровому объекту« Balletjes (Clone) »не прикреплен SpriteRenderer, но сценарий пытается получить к нему доступ».

Screen capture Inventory

Я бы хотел присвоить имя спрайта переменной goldCoinPopUp. Я много искал, но ничего не получалось. Может кто-нибудь помочь мне, пожалуйста?

ItemDragHandler

public class ItemDragHandler : MonoBehaviour, IDragHandler, IEndDragHandler
{

    public GameObject prefab;

    Vector2 original;

    public void OnDrag(PointerEventData eventData)
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Debug.DrawRay(ray.origin, ray.direction * 100);
        transform.position = Input.mousePosition;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray.origin, ray.direction, out hit, 100)) 
        {
            if (hit.collider.gameObject.name == "Terrain") 
            {
                transform.gameObject.SetActive(false);
                GameObject obj = Instantiate(prefab,hit.point, Quaternion.EulerAngles(0f, 3f, 0f)); // 3d object
                obj.AddComponent<GenerateResources>(); // link to GenerateResources script
                Vector3 img = new Vector3(0, 8.66f, 0);
                obj.transform.position += img;
            } 
            else 
            {
                transform.localPosition = original;
            }
        }
        else 
        {
            transform.localPosition = original;
        }
    }

    void Start () 
    {
        original = transform.localPosition;
    }
}

GenerateResources

public class GenerateRessources : MonoBehaviour 
{
    private int ressourcesInBuilding;

    public int valueWhenCollect = 10;

    private float timerExtraRessource;

    public float generateRate = 4;

    public SpriteRenderer goldCoinPopUp;

    private GameObject currentGameObject;

    private GameObject Inventory;

    void Start () 
    {
        goldCoinPopUp = GetComponent<SpriteRenderer>();
        goldCoinPopUp.enabled = false;
        currentGameObject = gameObject.GetComponent<GameObject>();
        Inventory = GameObject.Find("Inventory");
    }

    void Update () 
    {
        AddResource();
        getResources();
    }

    private void AddResource()
    {
        timerExtraRessource += Time.deltaTime;
        if (timerExtraRessource >= generateRate)
        {
            ressourcesInBuilding++;
            timerExtraRessource = 0;
            if (ressourcesInBuilding >= valueWhenCollect)
            {
                goldCoinPopUp.enabled = true;
            }
        }
    }

    private void getResources() 
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.touches[0];
            if (touch.phase == TouchPhase.Began)
            {
                RaycastHit hit;
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                if (Physics.Raycast(ray, out hit, 100f))
                {
                    if (hit.transform.gameObject != null)
                    {
                    }
                }
            }
        }
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit, 100f))
            {
                if (hit.transform.gameObject != currentGameObject)
                {
                    if (goldCoinPopUp.enabled == true)
                    {
                        goldCoinPopUp.enabled = false;
                        Inventory.GetComponent<GameController>().Gold += ressourcesInBuilding;
                        ressourcesInBuilding = 0;
                    }
                }
            }
        }
    }
}

1 Ответ

0 голосов
/ 09 января 2019

Ваш код зависит от присутствия SpriteRenderer, в то время как ваш префаб не имеет его. Вы можете обойти эту проблему, добавив следующий атрибут перед определением класса

[RequireComponent(typeof(SpriteRenderer))]
public class GenerateRessources : MonoBehaviour 

Однако к автоматически добавленному SpriteRenderer не будет прикреплен спрайт, поэтому лучшим решением было бы убедиться, что ваш префаб действительно имеет разумный спрайт

...