Hello,
I have this error kind of error:
"NullReferenceException: Object reference not set to an instance of an object
FloatingText.OnGUI () (at Assets/Scripts/FloatingText.cs:38)"
I know that it means that i'm trying to use something that is null, but I don't know how to fix it.
These are the classes i'm using:
FloatingText class
this is the class where the error is:
using UnityEngine;
public class FloatingText : MonoBehaviour {
private static readonly GUISkin Skin = Resources.Load("GUISkin");
public static FloatingText Show(string text, string style, IFloatingTextPositioner positioner)
{
var go = new GameObject("Floating Text");
var floatingText = go.AddComponent();
floatingText.Style = Skin.GetStyle(style);
floatingText._positioner = positioner;
floatingText._content = new GUIContent(text);
return floatingText;
}
private GUIContent _content;
private IFloatingTextPositioner _positioner;
public string Text
{
get
{
return _content.text;
}
set
{
_content.text = value;
}
}
public GUIStyle Style { get; set; }
public void OnGUI()
{
var position = new Vector2();
var contentSize = Style.CalcSize(_content); //ERROR
if(!_positioner.GetPosition(ref position, _content, contentSize))
{
Destroy(gameObject);
return;
}
GUI.Label(new Rect(position.x, position.y, contentSize.x, contentSize.y), _content, Style);
}
}
}
Interface:
using UnityEngine;
public interface IFloatingTextPositioner
{
bool GetPosition(ref Vector2 position, GUIContent content, Vector2 size);
}
FromWorldPointTextPosition class
using UnityEngine;
class FromWorldPointTextPosition
{
private readonly Camera _camera;
private readonly Vector3 _worldPosition;
private readonly float _speed;
private float _timeToLive;
private float _yOffset;
public FromWorldPointTextPosition(Camera camera, Vector3 worldPosition, float timeToLive, float speed)
{
_camera = camera;
_worldPosition = worldPosition;
_timeToLive = timeToLive;
_speed = speed;
}
public bool GetPosition(ref Vector2 position, GUIContent content, Vector2 size)
{
if ((_timeToLive -= Time.deltaTime) <= 0)
return false;
var screenPosition = _camera.WorldToScreenPoint(_worldPosition);
position.x = screenPosition.x - (size.x / 2);
position.y = Screen.height - screenPosition.y - _yOffset;
_yOffset += Time.deltaTime * _speed;
return true;
}
}
and this is the code I'm using for showing the floating text in some class:
FloatingText.Show(string.Format("+{0}!", blueGem.ValueGem),
"BlueGemText",
new FromWorldPointTextPosition(Camera.main, transform.position, 1.5f, 50) as IFloatingTextPositioner);
If I remove the as IFloatingTextPositioner); then I will get this error:
"cannot convert from "FromWorldPointTextposition' to "IFloatingTextPositioner"
and
"the best overloaded methode match for 'FloatingText.Show(...) has some invalid argument"
but by using this code it solved the error but I don't know if it will work if all the errors are solved.
Can someone help me?
Thank you in advance
Cynni
↧