Search Unity

Unity 2D c# Instantiate prefab transform not working

Discussion in '2D' started by Fendyk, Oct 7, 2017.

  1. Fendyk

    Fendyk

    Joined:
    May 12, 2017
    Posts:
    4
    So currently I am facing a issue. I have to files MatchManager.cs & playerHandler.cs. The playerhandler.cs is attached to a prefab called 'Player'.

    In my MatchManager.cs, I instantiate the Player.

    public void spawnPlayer()
    {
    if (Player != null)
    {
    Destroy(Player);
    }

    Player = Instantiate(PlayerPrefab, transform.position, Quaternion.identity) as GameObject;
    }

    It works fine however, when the player spawns, the playerHandler.cs is not working for some reason. For example, my speed variable wont increase when I use a onPointerDownBoost() event.

    Oh and just to be aware everything worked fine before I started working with prefabs so every variable or calculation in my playerHandler.cs should work.

    Is there a solution for this? If you need more specific details you can ask me.

    Thanks
     
  2. hlw

    hlw

    Joined:
    Aug 12, 2017
    Posts:
    250
    Well, I guess the problem is from the way you built your prefab and your playerHandler.cs (not 100% sure though). Maybe you had a reference on your player script that worked in the scene, but as a prefab, Unity can't find the referenced object.

    Can i see a screenshot of your prefab in the inspector, and your PlayerHandler.cs script ? (if the code is too long, consider posting it in the forum using the insert / code / c# - feature, by clicking on the button that looks like a newspaper page).
     
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    What is an onPointerDownBoost event, and where does it live?

    My guess is, this is a Unity event which is defined on some object in the scene, and which you imagine is hooked up to invoke a method on your newly-instantiated playerHandler. But it's not. Objects in the scene can't reference prefabs in the project, and when a prefab is instantiated, nothing in the scene references it. Any such references would have to be hooked up in code.

    This is not a bug; it's just how Unity works.