Getting Joystick to Control Instantiated Prefab

Updated on February 11, 2019 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on February 11, 2019

Hi there! I’ve followed the tutorial here on how to use the Virtual Joystick Package to move a player, but I was wondering how to attach it to a clone of the player that gets instantiated.

My scenario: I have a menu that contains a button that spawns a car. This button also disables the menu and enables the HUD (where the joystick lives). I’d like to now be able to use the joystick to control this instantiated car, but have to pause the game and drag the joystick from the hierarchy into the joystick inspector slot for it to function on my car.

I’ve tried attaching the joystick prefab to the player prefab (not expecting it to work) and have also looked extensively on Google for an answer… but I might be too much of a noob to wrap my brain around it. I’m sure the answer is actually quite simple (especially for you folks!) Can anyone point me in the right direction at least? I’d really appreciate it. =) Thanks in advance!

  • Liked by
0 on February 11, 2019

I’ve never used a virtual joystick but the way it s set up in that video I would suggest creating a script for your car’s movement, within that script you can search for the virtual joystick within the script’s Start method.

If you are really new you may want to read up on a few things that are super useful:

Start: Start is called before the first frame update only if the script instance is enabled.”

This can be found here if you want to read more into these functions. You don’t particularly need to read and memorize the whole thing because there is certainly a lot gong on, but it’s really good to know how the first few subheadings work.

This isn’t the most efficient method of doing what you want to do, but you only need to call it once so I would suggest using this. It will search the hierarchy for gameobjects matching the name you pass in as a parameter.

Joystick joystick;
void Start(){
    joystick = GameObject.Find("Joystick");
  • Liked by