Skip to content

Commit

Permalink
Merge pull request #660 from NordlightPer/fix/set_prefab_back_to_acti…
Browse files Browse the repository at this point in the history
…ve_on_exception

Added test and fix for when a game object throws during instantiation
  • Loading branch information
hadashiA authored Apr 28, 2024
2 parents 897c47f + d3e25db commit bfc5e58
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System;
using UnityEngine;

namespace VContainer.Tests.Unity
{

public sealed class CrashingSampleMonoBehaviour : MonoBehaviour, IComponent
{
public ServiceA ServiceA;
public ServiceA ServiceAInAwake;
public bool StartCalled;
public int UpdateCalls;

void Start() => StartCalled = true;
void Update() => UpdateCalls += 1;

void Awake()
{
ServiceAInAwake = ServiceA;
}

[Inject]
public void Construct(ServiceA serviceA)
{
ServiceA = serviceA;
throw new Exception("Something broke during construct");
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions VContainer/Assets/Tests/Unity/UnityObjectResolverTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Reflection;
using NUnit.Framework;
using UnityEngine;
using VContainer.Unity;
Expand Down Expand Up @@ -141,6 +142,22 @@ void AssertInstantiatedInstance(SampleMonoBehaviour instance)
Assert.That(instance.ServiceA, Is.InstanceOf<ServiceA>());
}
}

[Test]
public void WhenFailingDuringInstantiateGameObject_TheGameObjectIsStillEnabled()
{
var builder = new ContainerBuilder();
builder.Register<ServiceA>(Lifetime.Singleton);
var container = builder.Build();

var parent = new GameObject("Parent");
GameObject original = new GameObject("Original");
original.AddComponent<CrashingSampleMonoBehaviour>();

Assert.Catch(() => container.Instantiate(original, parent.transform));

Assert.That(original.gameObject.activeSelf, Is.True);
}

[Test]
public void Instantiate_ExceptionThrownDuringInjection_PrefabIsStillEnabled()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,14 +183,18 @@ public static GameObject Instantiate(this IObjectResolver resolver, GameObject p
var wasActive = prefab.activeSelf;
prefab.SetActive(false);

var instance = UnityEngine.Object.Instantiate(prefab, parent, worldPositionStays);
SetName(instance, prefab);

resolver.InjectGameObject(instance);

prefab.SetActive(wasActive);
instance.SetActive(wasActive);

GameObject instance = null;
try
{
instance = UnityEngine.Object.Instantiate(prefab, parent, worldPositionStays);
SetName(instance, prefab);
resolver.InjectGameObject(instance);
}
finally
{
prefab.SetActive(wasActive);
instance?.SetActive(wasActive);
}
return instance;
}

Expand Down

0 comments on commit bfc5e58

Please sign in to comment.