- Home /
Game freezing after adding game objects with OnMouseDown () to control movement of character rather than mouse keys
In my game i want it to be eventually made controllable by touch for mobile devices. So first i plan to make everything controllable by mouse then just switch it over. So instead of moving my player with arrow keys to dodge instantiated obstacles i was going to click an object which would work the same as pressing a mouse key. After struggling with event systems and UI buttons, listeners, etc, i decided to create a game object with code which would happen when it was clicked. Hence the code below.
For left object
using UnityEngine;
using System.Collections;
public class Leftt : MonoBehaviour {
public new Vector3 position;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnMouseDown () {
Debug.Log ("Left");
GameObject player = GameObject.Find("Player");
Movement playerScript = player.GetComponent<Movement>();
position = playerScript.position;
if (position == new Vector3(0,1,-40))
{
playerScript.transform.position = new Vector3(-10,1,-40);
}
if (position == new Vector3(10,1,-40))
{
playerScript.transform.position = new Vector3(0,1,-40);
}
}
}
For right object
using UnityEngine;
using System.Collections;
public class Rightt : MonoBehaviour {
public new Vector3 position;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnMouseDown () {
Debug.Log ("Right");
GameObject player = GameObject.Find("Player");
Movement playerScript = player.GetComponent<Movement>();
position = playerScript.position;
if (position == new Vector3(0,1,-40))
{
playerScript.transform.position = new Vector3(10,1,-40);
}
if (transform.position == new Vector3(-10,1,-40))
{
playerScript.transform.position = new Vector3(0,1,-40);
}
}
}
I then played it and at first the code was working and i just clicked the object like pressing left and right arrow keys but then the instantiated objects (obstacles to dodge) came and the controls stopped. I guess freezing up because of spikes in CPU of sorts which seemed to happen in the profiler. I know this has to be because of my change of controls because it worked before with arrow keys. But 'why would that make a difference and what can i do to solve it?' i wandered and now i am asking you.
Thank you for any answers this is the last thing i need to do in completing my game which i have spent a long time on. Answers/ help much needed. :-)
Update - looking at profiler wanting to work it out, trying to attach screenshots.
Your answer