dimanche 28 avril 2019

'new' operator log warning when creating a GameObject, how to get around it?

Im wondering about something I am doing that is causing this well known warning:

You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all.

I know that I can simply use the Addcomponent<T> to avoid that logwarning. I also understand that unity does not allow anything inheriting from monobehaviour to be instantiated (ref).

It should be said however that right now the tests providing this logwarning are all working fine, I just want to get rid of the warning.

This is an example of a test that gives this error.

[Test]
public void HandleHoverSetsCurrentInteractableOnInteractor()
{
    /// Arrange
    GameObject actor;
    actor = new GameObject();
    actor.AddComponent<XRController>();

    GameObject actable;
    actable = new GameObject();
    Handle h = actable.AddComponent<Handle>();
    h.Hover(actor.GetComponent<IActor>());

    /// Assert
    Assert.IsNotNull(actor.GetComponent<IActor>().currentInteractable);
}

Now as mentioned earlier this works exactly as I would expect and it is creating the GameObject and testing the Hover functionality. It's just giving me that logwarning every time I do this. I am therefore wondering if there is a correct way of doing this? preferably without the logwarning.

Aucun commentaire:

Enregistrer un commentaire