2017-06-26 117 views
1

我最近開始學習使用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"); 
     } 
    } 
} 
+0

的' Start()方法在對象啓動時自動調用。每個幀都運行Update()。當場景(或對象被創建)開始時,您將禁用敵人,然後如果mousePosInBlocks等於或小於6.5,您將其激活。如果您不確定mousePosInBlocks的值,可以執行'Debug.Log(mousePosInBlocks)' – Maakep

回答

4

當您從不打電話給enemy.SetActive(false);時,您是如何期待該對象被禁用的?它只在Start方法中調用,但這將被enemy.SetActive(true);覆蓋,每幀在Update方法中調用。

我不確定何時應禁用對象,但只需在相應的if語句中添加enemy.SetActive(false);即可。

1

你必須添加代碼行來禁用更新類中的對象,因爲你說它應該被禁用,當你移動鼠標超出範圍,我猜這條線應該在你的其他狀態

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 
     { 
      enemy.SetActive(false); 
      print("4"); 
     } 
    } 
} 

在你只需要添加enemy.SetActive(false);裏面的如果,如果,否則,否則statament,確保它裏面的任何情況下,否則會得到每一幀中調用,它會留下殘疾