我最近開始學習使用C#編寫Unity代碼;在下面的腳本中試圖根據鼠標的位置啓用和禁用一個對象(敵人)。C#統一語句邏輯
問題是代碼在啓用對象時工作正常,但我無法弄清楚如何禁用它,一旦它被激活,使對象出現並隨着鼠標來回移動而出現並消失的範圍。請讓我知道你是否有解決方案。謝謝!
using UnityEngine;
using System.Collections;
public class Paddle : MonoBehaviour
{
public GameObject enemy;
// Use this for initialization
void Start()
{
enemy.SetActive(false);
}
// Update is called once per frame
void Update()
{
Vector3 paddlePos = new Vector3(8f, this.transform.position.y, 0f);
float mousePosInBlocks = Input.mousePosition.x/Screen.width * 16;
paddlePos.x = Mathf.Clamp(mousePosInBlocks, 6f, 8f);
this.transform.position = paddlePos;
if (mousePosInBlocks < 6f)
{
print("1");
}
else if (mousePosInBlocks <= 6.5f)
{
print("2");
enemy.SetActive(true);
}
else if (mousePosInBlocks <= 7.5f)
{
print("3");
}
else
{
print("4");
}
}
}
的' Start()方法在對象啓動時自動調用。每個幀都運行Update()。當場景(或對象被創建)開始時,您將禁用敵人,然後如果mousePosInBlocks等於或小於6.5,您將其激活。如果您不確定mousePosInBlocks的值,可以執行'Debug.Log(mousePosInBlocks)' – Maakep