Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How do i add a prefab into my game using code?

Discussion in 'Scripting' started by MammothSaturn83, Apr 4, 2019.

  1. MammothSaturn83

    MammothSaturn83

    Joined:
    Feb 10, 2018
    Posts:
    20
    I am having issues with my script where i wan't to add a prefab called "Wall" into the game using the player current position but the script will not add the prefab into the game.

    Here is my code:
    //Variables
    public GameObject Wall;
    public GameObject Floor;
    public GameObject BuildingUI;
    private bool MenuActive = false;
    public GameObject Player;
    public void Start()
    {
    Wall.transform.localPosition = Player.transform.localPosition;
    }
    public void Update()
    {
    if (Input.GetKeyDown(KeyCode.B))
    {
    if (MenuActive == false)
    {
    MenuTrue();
    } else
    {
    MenuFalse();
    }
    }
    if (WallSelected == true && tag == "Player")
    {
    ImportWall();
    }
    }
    public void MenuTrue()
    {
    GameObject.Find("Player").GetComponent<FirstPersonController>().enabled = false;
    BuildingUI.SetActive(true);
    Time.timeScale = 0f;
    Cursor.visible = true;
    Cursor.lockState = CursorLockMode.None;
    MenuActive = true;
    }
    public void MenuFalse()
    {
    GameObject.Find("Player").GetComponent<FirstPersonController>().enabled = true;
    BuildingUI.SetActive(false);
    Time.timeScale = 1f;
    Cursor.visible = false;
    Cursor.lockState = CursorLockMode.Locked;
    MenuActive = false;
    }
    public void ImportWall()
    {

    }
    ----------------------------------------------------------
    Any help would be very helpful, Thankyou Nick
     
  2. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,905
    You're using "Wall" in the Start() method, so you must have dragged a reference in the Inspector. Otherwise it would be null and you would get errors.

    If you drag a prefab from the Project view into the value for Wall, then it is a valid prefab reference. You don't want to position the Wall which is a prefab reference, because it's not really part of your Scene. You want to Instantiate(Wall,...) to make a clone of the prefab into the Scene. Then you can move the clone around.

    But I also notice you're trying to set the wall's .localPosition, which doesn't do what you think it does. To position things in the Scene, you want to be working with the .position instead of .localPosition field.
     
  3. MammothSaturn83

    MammothSaturn83

    Joined:
    Feb 10, 2018
    Posts:
    20
    Thanks that worked, but how would i reference its position to equal the players position?
     
    Last edited: Apr 4, 2019