Instantiate character runtime from code

TrungDong

Member
I made the character, main camera, UI, virtual control, managers ... into a prefab, like this image:

Screen Shot 2018-12-14 at 2.24.49 AM.png

I put the prefab into the scene. The game runs fine in the Editor, also fine in my device (iPhone).

For some reasons, I have to instantiate my character runtime from code, at a specific time/event. Instead of putting the prefab into the scene, I load the prefab when it is needed.
Everything was fine on the Editor, but when I run the game on my device, the virtual controls do not appear, and if I touch the screen:
+ 1 finger: the player shot (= left click).
+ 2 fingers touch: the player zoom (= right click)
It seems the virtual controls did not work, and the game uses pc input instead.

How to fix this? Is it required to have all character's related objects in the scene from the start? In my case (I want to load character at a event)
 
On your character prefab did you make sure to specify virtual for the Force Input type on the Unity Input component?
 
When you instantiate the character did you assign the character to the VirtualControlsManager? It doesn't look like that has a property for the character but you can add it:

Code:
        public GameObject Character { get { return m_Character; } set { OnAttachCharacter(value);  } }
I just tested this and was able to get it working.
 
I have found the cause.
In my case, I want to use Standalone Input at Editor (easier to test), Visual Input at the real device. So I disabled CanvasVirtualControl by default, and enable it when the game run in the device.
That made FindObjectOfType<VirtualControlsManager>() (UnityInput.cs line 60) return null because the time when it finds object, the VirtualControlsManager is not enabled yet, and the function FindObjectOfType cannot find inactive object.
So the input is always instantiated as a Standalone input, which is the cause of the strange behavior on my device.
To fix this, set CanvasVirtualControl enable by default, or use FindObjectsOfTypeAll instead of FindObjectOfType.
 
Top