因此,我從我的游戲中撰寫了一個抓斗(代碼來自一個稍作調整的教程),并且我試圖在顯示頂部的抓斗頂部實體化一個預制件。它目前只是一個帶有精靈渲染器的空物件。抓斗正在作業,我只需要弄清楚當我不按下抓斗按鈕時如何洗掉物件。
代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class grapple : MonoBehaviour
{
public Camera mainCamera;
public LineRenderer _lineRenderer;
public DistanceJoint2D _distanceJoint;
public Transform target;
// Start is called before the first frame update
void Start()
{
_distanceJoint.enabled = false;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(1))
{
Vector2 mousePos = (Vector2)mainCamera.ScreenToWorldPoint(Input.mousePosition);
_lineRenderer.SetPosition(0, mousePos);
_lineRenderer.SetPosition(1, transform.position);
_distanceJoint.connectedAnchor = mousePos;
_distanceJoint.enabled = true;
_lineRenderer.enabled = true;
Instantiate(target, mousePos, Quaternion.identity);
//if (Input.GetKey("Space"))
//{
//transform.position = Vector2.MoveTowards(transform.position, target.position, 4 * Time.deltaTime);
//}
}
else if (Input.GetMouseButtonUp(1))
{
_distanceJoint.enabled = false;
_lineRenderer.enabled = false;
Destroy(target);
}
if (_distanceJoint.enabled)
{
_lineRenderer.SetPosition(1, transform.position);
}
}
}
uj5u.com熱心網友回復:
將實體化的物件保存到類成員變數中,并用于以后銷毀
GameObject _instantiatedObj;
void Update()
{
if (Input.GetMouseButtonDown(1))
{
Vector2 mousePos = (Vector2)mainCamera.ScreenToWorldPoint(Input.mousePosition);
_lineRenderer.SetPosition(0, mousePos);
_lineRenderer.SetPosition(1, transform.position);
_distanceJoint.connectedAnchor = mousePos;
_distanceJoint.enabled = true;
_lineRenderer.enabled = true;
_instantiatedObj = Instantiate(target, mousePos, Quaternion.identity);
//if (Input.GetKey("Space"))
//{
//transform.position = Vector2.MoveTowards(transform.position, target.position, 4 * Time.deltaTime);
//}
}
else if (Input.GetMouseButtonUp(1))
{
_distanceJoint.enabled = false;
_lineRenderer.enabled = false;
Destroy(_instantiatedObj);
}
if (_distanceJoint.enabled)
{
_lineRenderer.SetPosition(1, transform.position);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/494710.html
上一篇:從物件陣列中洗掉多個物件