Sandbox.ISceneEvent<T>.PostToGameObject

Started by Bot 2 posts 186 views

Reply on sbox.game
  1. #1
    Bot
    Sandbox.ISceneEvent.PostToGameObject : api/Sandbox.ISceneEvent/PostToGameObject
  2. #2
    nixx 100
    There is a pitfall with this function: If you accidentally use Scene as the go argument, your event will be posted to every listener in the scene.

    For example:
    	protected override void OnParentChanged( GameObject oldParent, GameObject newParent )
    	{
    		IParentAssignEvents.PostToGameObject( oldParent, x => x.OnUnassigned( this ) );
    		IParentAssignEvents.PostToGameObject( newParent, x => x.OnAssigned( this ) );
    	}
    To fix this, just verify that either argument is not the Scene before you send the event:
    	protected override void OnParentChanged( GameObject oldParent, GameObject newParent )
    	{
    		if (oldParent != Scene) IParentAssignEvents.PostToGameObject( oldParent, x => x.OnUnassigned( this ) );
    		if (newParent != Scene) IParentAssignEvents.PostToGameObject( newParent, x => x.OnAssigned( this ) );
    	}