0
votes

I have a GameObject called 'Player' with a GameObject called 'FirePoint':

Screenshot of Player GameObject

Further I wrote a very basic c# Script 'Weapon':

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Weapon : MonoBehaviour
{

    public Transform firePoint;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}

I dragged the script on the Player GameObject and now it is shown in the Inspector. Within the Script I would like to use the FirePoint, that is in Player. The only way to do so I know is, to drag the FirePOint into the place holder:

Weapon Script in Player Inspector

I want to avoid the manual drag and drop, because I want to spawn new Players with their own FirePoints during the game. How can I do that programmatically? I could not find any tutorial (maybe because I don't know how to search for it), so I would also be glad to have a link to an easy tutorial that addresses this problem.

2

2 Answers

2
votes

You're likely looking at using prefabs and instantiating them at runtime.

Unity’s Prefab system allows you to create, configure, and store a GameObject complete with all its components, property values, and child GameObjects as a reusable Asset. The Prefab Asset acts as a template from which you can create new Prefab instances in the Scene .

Prefabs allow you to build a GameObject as a template, and create a clone of it at runtime. When instantiating an object, it happens in code and can be assigned within the code itself. You can assign the firePoint in your player prefab once, and any time you instantiate or clone the prefab it will have its own firePoint created and assigned.

0
votes

Besides the Prefab already suggested by Erik Overflow:

The "proper" way in general programming would be: Have a class on your firePoint object like

// The class doesn't have to do anything, it is just for identification
public class FirePoint : MonoBehaviour { }

and then use

public class Weapon : MonoBehaviour
{
    public FirePoint firePoint;
}

This forces the referenced GameObject to have a FirePoint component and makes sure you don't reference something else here by accident.

And now you can also simply get it on runtime in case you forget/don't want to reference it manually

private void Awake ()
{
    if(!firePoint) firePoint = GetComponentInChildren<FirePoint>(true);
}