Skip to content

Inconsistent AddTo behavior between active and inactive GameObjects #354

@kyubuns

Description

@kyubuns

When a GameObject is inactive at initialization time, AddTo(this) behaves differently compared to when the GameObject is active.

Reproduction Steps

  1. Create a new GameObject named “Test” and attach the following script:
using R3;
using UnityEngine;

public class Test : MonoBehaviour
{
    public Subject<Unit> Subject { get; } = new();

    public void Initialize()
    {
        Debug.Log("Initialize");

        Subject.Subscribe(_ =>
        {
            Debug.Log($"Called! {this != null}");
            gameObject.name = "hoge";
        }).AddTo(this);

        Disposable.Create(() =>
        {
            Debug.Log("Destroy");
        }).AddTo(this);
    }
}
  1. Deactivate the “Test” GameObject in the Hierarchy.

  2. Create another GameObject named “TestCall” and attach the following script:

using System.Linq;
using Cysharp.Threading.Tasks;
using R3;
using UnityEngine;

public class TestCall : MonoBehaviour
{
    public void Start()
    {
        var t = FindObjectsByType<Test>(FindObjectsInactive.Include, FindObjectsSortMode.InstanceID).Single();
        t.Initialize();

        UniTask.Void(async () =>
        {
            await UniTask.NextFrame();

            Destroy(t.gameObject);

            await UniTask.DelayFrame(0, PlayerLoopTiming.LastUpdate);

            t.Subject.OnNext(Unit.Default);
        });
    }
}
  1. Run the scene.

Actual Behavior

When the “Test” GameObject is inactive, the following log appears and a MissingReferenceException is thrown:

Initialize
Called! False
MissingReferenceException: The object of type 'Test' has been destroyed but you are still trying to access it.
Destroy

Expected Behavior

No exception should occur.
When the “Test” GameObject is active, everything works as expected:

Initialize
Destroy

Environment

  • Unity 6000.0.28
  • R3 1.3.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions