仅在按下按钮时显示GUI纹理?

时间:2016-11-16 19:06:14

标签: c# user-interface unity3d

此脚本在按下"Fire2"时控制相机FOV以及显示GUI纹理。但是,一旦用户按下按钮一次,纹理就会显示并且不会消失,直到再次按下该按钮 - 我希望它仅在按下按钮时显示?此脚本附加到预制件,该预制件是播放器预制件的子对象。我试图使用GetButton,但看到每个帧都调用OnGUI()以及Update()函数,它只会使纹理闪烁。

using UnityEngine;
using System.Collections;
 
public class awpScopeIn : MonoBehaviour {
 
    public Texture scopeGUI;
    private bool _isScoped = false;
    public Color color = Color.black;
    private Camera cam;
    public GameObject awp_graphics;
 
    void Start()
    {
        cam = GetComponentInParent( typeof(Camera) ) as Camera;
        cam.clearFlags = CameraClearFlags.SolidColor;
        cam.fieldOfView = 70f;
    }
   
    void OnGUI()
    {
        float width = 600;
        float height = 600;
       
        if (_isScoped) {
            GUI.DrawTexture (new Rect ((Screen.width / 2) - (width/2), (Screen.height / 2) - (height/2), width, height), scopeGUI);  
        }
    }
   
    void Update()
    {
        if(Input.GetButtonDown("Fire2"))
        {
            _isScoped = !_isScoped;
            cam.backgroundColor = color;
            cam.fieldOfView = 45f;
            awp_graphics.gameObject.SetActive(false);
        }else if(Input.GetButtonUp("Fire2"))
        {
            cam.fieldOfView = 70f;
            awp_graphics.gameObject.SetActive(true);
        }
   
    }
}

1 个答案:

答案 0 :(得分:0)

您只是在按下按钮时更改值,但是在释放按钮时必须更新显示纹理的标志。所以你的Update方法应该是:

if(Input.GetButtonDown("Fire2"))
    {
        _isScoped = !_isScoped;
        cam.backgroundColor = color;
        cam.fieldOfView = 45f;
        awp_graphics.gameObject.SetActive(false);
    }else if(Input.GetButtonUp("Fire2"))
    {
        cam.fieldOfView = 70f;
        awp_graphics.gameObject.SetActive(true);
        _isScoped = false;
    }