- Home /
C# Joystick GetComponent();
An error occurs when you start. Error: NullReferenceException: Object reference not set to an instance of an object CubeController.Update () (at Assets/Scripts/CubeController.cs:16); Please tell me where my mistake.
Script C# IController.cs
public interface IInputController
{
float GetHorizontal();
}
Script C# CubeController.cs
using UnityEngine;
using System.Collections;
public class CubeController : MonoBehaviour {
public IInputController InputController;
// Use this for initialization
void Start () {
InputController = PickInputController ();
}
// Update is called once per frame
void Update () {
transform.Rotate (new Vector3(InputController.GetHorizontal(), 0, 0) );
}
private IInputController PickInputController ()
{
#if UNITY_ANDROID
var temp = GetComponent<UIController>();
return temp;
#endif
}
}
Script C# UIController.cs
using UnityEngine;
using System.Collections;
public class UIController : MonoBehaviour, IInputController {
public Texture2D TextUpArrow;
public Texture2D TextDownArrow;
private Rect _upArrow;
private Rect _downArrow;
private float _vertical;
private float _width;
void OnGUI()
{
if (Screen.width != _width)
{
int prc = (Screen.height / 100) * 25;
_upArrow = new Rect(25, Screen.height - prc * 2, prc, prc);
_downArrow = new Rect(25, Screen.height - prc, prc, prc);
_width = Screen.width;
}
GUI.DrawTexture (_upArrow, TextUpArrow);
GUI.DrawTexture (_downArrow, TextDownArrow);
}
public float GetHorizontal()
{
bool downArrowTouch = IsTouchContains (_downArrow);
bool upArrowTouch = IsTouchContains (_upArrow);
if (downArrowTouch || upArrowTouch)
{
if (downArrowTouch)
{
if (_vertical < 1)
{
_vertical += Time.deltaTime * 3;
Debug.Log(_vertical);
}
}
else
{
if (upArrowTouch)
{
if (_vertical > -1)
{
_vertical -= Time.deltaTime * 3;
Debug.Log(_vertical);
}
}
}
}
else
{
_vertical = Mathf.Lerp (_vertical, 0, Time.deltaTime * 5);
}
Debug.Log (_vertical);
return _vertical;
}
private bool IsTouchContains(Rect area)
{
bool isCont = false;
foreach (Touch touch in Input.touches)
{
Vector3 tPos = touch.position;
tPos.y = Screen.height - tPos.y;
if (area.Contains(tPos))
{
isCont = true;
Debug.Log(isCont);
}
}
Debug.Log(isCont);
return isCont;
}
}
Answer by hexagonius · Oct 03, 2015 at 03:54 PM
I would say that PickInputController in CubeController returns null. u sure the gameobject with CubeController also has the UIController script attached?
I know English bad. CubeController.cs I add the gameobject Cube. UIController.cs add $$anonymous$$ainCamera. whether I do?
ins$$anonymous$$d
var temp = GetComponent<UIController>();
do
var temp = Camera.main.GetComponent<UIController>();
Your answer
Follow this Question
Related Questions
3rd person to 1st person view with two engines 0 Answers
I survival shooting player not moving 0 Answers
addforce please 0 Answers
Character controller stops walking in middle of air 0 Answers
How to detect what layer is colliding 0 Answers