当前位置:编程学习 > 网站相关 >>

Unity3d 通过代码手动创建button(不用GUI自带的button以及其他插件)

using Liulala.Utils;

using UnityEngine;

 

public class Button : MonoBehaviour

{

protected virtual void OnMoveOver()

{

}

 

protected virtual void OnMoveOut()

{

}

 

protected virtual void OnPressDown()

{

}

 

protected virtual void OnPressUp()

{

}

 

protected bool IsButtonPressed { get { return _isButtonPressed; } }

 

protected bool IsButtonHovered { get { return _isButtonHovered; } }

 

protected virtual void Awake()

{

if (_buttonCollider == null)

{

_buttonCollider = GetComponent<Collider>();

if (_buttonCollider == null)

{

_buttonCollider = GetComponentInChildren<Collider>();

if (_buttonCollider)

{

Debug.LogError("Couldn't find a collider for button");

}

}

}

}

 

protected virtual void Update()

{

if (HitButtonArea())

{

_isButtonHovered = true;

if (!PlatformUtil.IsTouchDevice)

{

OnMoveOver();

}

 

if (GameControl.Input.IsClickDown)

{

_isButtonPressed = true;

OnPressDown();

}

else if (GameControl.Input.IsClickUp && _isButtonPressed)

{

_isButtonPressed = false;

OnPressUp();

}

}

else if (_isButtonHovered)

{

_isButtonHovered = false;

OnMoveOut();

}

}

 

private bool HitButtonArea()

{

if (GameControl.Input.HasTouch)

{

Ray ray = Camera.main.ScreenPointToRay(GameControl.Input.MousePosition);

RaycastHit hit;

if (Physics.Raycast(ray, out hit, float.PositiveInfinity, ~LayerMask.NameToLayer("UI")))

{

return hit.collider == _buttonCollider;

}

}

return false;

}

 

[SerializeField]

private Collider _buttonCollider;

private bool _isButtonHovered;

private bool _isButtonPressed;

}

 

其他脚本继承于button脚本。


using UnityEngine;

using System.Collections;

 

public class StartButton : Button

{

    protected override void Awake()

    {

        base.Awake();

 

        _quadMesh = GetComponent<QuadMesh>();

    }

 

    protected override void OnMoveOut()

    {

        _quadMesh.Texture = _normalTexture;

    }

 

    protected override void OnPressDown()

    {

        _quadMesh.Texture = _activeTexture;

    }

 

    protected override void OnPressUp()

    {

        _quadMesh.Texture = _normalTexture;

 

        Application.LoadLevel("Main");

    }

 

    [SerializeField]

    private Texture2D _normalTexture;

    [SerializeField]

    private Texture2D _activeTexture;

 

    private QuadMesh _quadMesh;

}

 


 

补充:综合编程 , 其他综合 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,