首页 > 解决方案 > 似乎无法统一使用 Vector3 获得玩家位置

问题描述

我将如何获得玩家的位置,以便我可以将物品放在玩家前方约 5 个单位的位置,这样他们就不会在放下物品后立即拿起物品,以及我如何获得玩家的 Vector3 位置以及尝试多种方式我仍然无法让它工作我正在尝试在这里做:

        public void DropItem()
    {
        if(slotsItem)
        {
            slotsItem.transform.parent = null;
            slotsItem.gameObject.SetActive(true);
            slotsItem.transform.position = Vector3.lastpos;
        }

那么这里也是完整的代码

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

public class Slot : MonoBehaviour
{
    public Item slotsItem;
    public Transform player;

    Sprite defaultSprite;
    Text amountText;

    public void CustomStart()
    {
        defaultSprite = GetComponent<Image>().sprite;
        amountText = transform.GetChild(0).GetComponent<Text>();
        this.player = GameObject.FindWithTag("Player").transform;
        Vector3 lastpos = player.position;
    }

    public void DropItem()
    {
        if(slotsItem)
        {
            slotsItem.transform.parent = null;
            slotsItem.gameObject.SetActive(true);
            slotsItem.transform.position = Vector3.lastpos;
        }
    }

    public void CheckForItem()
    {
        if(transform.childCount > 1)
        {
            slotsItem = transform.GetChild(1).GetComponent<Item>();
            GetComponent<Image>().sprite = slotsItem.itemSprite;
            if(slotsItem.amountInStack > 1)
                amountText.text = slotsItem.amountInStack.ToString();

        }
        else
        {
            slotsItem = null;
            GetComponent<Image>().sprite = defaultSprite;
            amountText.text = "";
        }
    }
}

标签: c#unity3d

解决方案


应该是什么Vector3.lastpos

我认为您宁愿在课堂上存储一个字段

private Vector3 lastpos;

将此字段分配给

public void CustomStart()
{
    ...

    lastpos = player.position;
}

然后像以后一样使用它

public void DropItem()
{
    ...

        slotsItem.transform.position = lastpos;

    ...
}

虽然问题是为什么不简单地使用当前位置

slotsItem.transform.position = player.position;

推荐阅读