- Home /
Alternative to SendMessage()? / Mobile Optimization
My targeted platform is Windows Phone 8 and this function seems to cause quite a lot of lag. It drops the game from around 45 to 2. The scripts I have for the movement buttons are the following:
using UnityEngine;
using System.Collections;
public class TouchButton : MonoBehaviour {
// Update is called once per frame
void Update () {
if(Input.touches.Length <= 0) {
}
else {
for(int i = 0; i < Input.touchCount; i++) {
if(this.guiTexture.HitTest(Input.GetTouch(i).position)) {
if(Input.GetTouch(i).phase == TouchPhase.Began) {
Debug.Log("The touch has begun on " + this.name);
this.SendMessage("OnTouchBegan");
}
if(Input.GetTouch(i).phase == TouchPhase.Ended) {
Debug.Log("The touch has ended on " + this.name);
this.SendMessage("OnTouchEnded");
}
}
}
}
}
}
This one has multiple versions of it, one for every button on screen. (4 different)
using unityEngine;
using System.Collections;
public class TouchButtonBackward : TouchButton {
void OnTouchBegan() {
PlayerMovement.backward = 1;
}
void OnTouchEnded() {
PlayerMovement.backward = 0;
}
}
Answer by Benproductions1 · Dec 27, 2013 at 02:12 AM
Hello,
What send message does, is use reflection on every component of the object you are calling it on to find the function using it's name for comparison and then calls it.
It translates to something like this:
//Yes it's UnityScript. I find it easier
function SendMessage(name:String) {
var components:Component[] = GetComponents<Component>();
for (var component:Component in components) {
CallMethod(component, name);
}
}
private function CallMethod(object:Object, name:String) {
var type:Type = object.GetType();
var method:MethodInfo = type.GetMethod(name);
method.Invoke(object, null);
}
If you're writing a closed system, it would be much easier to call the functions directly, instead of using SendMessage
.
So something like this:
GetComponent<TouchButtonBackward>().OnTouchBegan()
Hope this helps,
Benproductions1
Your answer
Follow this Question
Related Questions
Unity3.4 Mobile Terrain Lag 1 Answer
Touch Input only working on Unity Remote 0 Answers
Why is my camera motion so jittery? 3 Answers
Why did my render time increase after lowering the vertex count? 2 Answers
Reflect Fresnel Mobile VR 0 Answers