'2018/03'에 해당되는 글 1건

  1. 2018/03/04 글뻥 How to reduce the code when you use the uGUI on Unity3D
If you use the uGUI for making mobile UI Event, perhaps, Your code like below code.

* button script (Example): Mobile has just 3 events. Pressed, Exit from a button (Cancel), Deattached from a button (OK).

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class CommonButton : MonoBehaviour, IPointerDownHandler, IPointerExitHandler, IPointerClickHandler {

GameObject selectedObject;
 
//Process for Selected button
public void OnPointerDown(PointerEventData eventData) {
selectedObject = gameObject;
//Blah blah... something
}

//Process for cancel button
public void OnPointerExit(PointerEventData eventData) {
selectedObject = null;
//Blah blah... something
}

//Process for OK button
public void OnPointerClick(PointerEventData eventData) {
if (selectedObject != gameObject) return;
selectedObject = null;
//Blah blah... something
}
}


Normally, We attach this code @ each button object.
It is terrible for maintenance.

If someone wants to change some behavior, We should change all.

however, we could solve this problem by simple Inheritance.

1. Make a parents class for sharing.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class CommonButton : MonoBehaviour, IPointerDownHandler, IPointerExitHandler, IPointerClickHandler {

 GameObject selectedObject;

 public void OnPointerDown(PointerEventData eventData) {
 selectedObject = gameObject;
 PressedButton();
 }

 public void OnPointerExit(PointerEventData eventData) {
 selectedObject = null;
 CancelButton();
 }

 public void OnPointerClick(PointerEventData eventData) {
 if (selectedObject != gameObject) return;
 selectedObject = null;
 OKButton();
 }

 public virtual void PressedButton() { } //Virtual method is key point
 public virtual void CancelButton() { }
 public virtual void OKButton() { }
}


2. Make a child class for attaching to each button.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BehaviourRadioMenus : CommonButton {

 override public void PressedButton() {
 RevealDesc();
 }

 override public void CancelButton() {
 HideDesc();
 }

 override public void OKButton() {
 HideDesc();
 }

 void RevealDesc() {
 }

 void HideDesc() {
 }
}


Cheers!
2018/03/04 06:27 2018/03/04 06:27