How to add asset into scene via script

I have downloaded an asset from Unity’s store (it’s shotgun), how can I add it into my scene via code?

presumably the shotgun came as a prefab. Find the prefab, make sure it is in the Resources folder somewhere

Then:

(GameObject)Instantiate(Resources.Load("path/shotgun"), position, rotation);

Where position is a Vector3 indicating where to make the shotgun appear, and rotation is a Quaternion indicating the rotation.

Hi, you can also create a prefab with your asset setup how you need, then assign it in a script like this:

//C# Code
class                             AssetSpawner : MonoBehaviour
{
      public Transform            _theAsset;
      public Vector3              _spawnPosition;

      //Call this.Spawn() from Start() or Update() or whereever your logic triggers the spawn of the asset
      void                        Spawn()
      {
            Transform             instanciatedAsset;

            instanciatedAsset = (Transform)Instantiate(this._theAsset, this._spawnPosition, Quaternion.identity);
            //Do stuff with your instanciatedAsset ...
      }
}

You should checkout the documentation (here) about the subject for more details and how-tos.

So what’s my path, “semi-automatic rifle/SAR”? Because it does not work

1517972--86602--$e43b879b3f2f1fdff92b4f18703e7961.png

probably semi-automatic rifle/prefab/somethingsomething

Shotgun = Instantiate( Resources.Load( "semi-automatic rifle/prefab/SARP" ) );

Error: ArgumentException: The thing you want to instantiate is null.

It has to be in a folder called Resources in order for Resources.Load to work.

Do I create this folder in projetc’s main directory?

It can be anywhere in your project and you can have more than one.

There’s completely no way to simulate this ‘drag n drop’ in Editor, always I’ll have to copy my asset to Resource folder?

You can do it by assigning references directly, as in _met44’s example. Just drag the prefab directly from the library onto the _theAsset field.

thanks buddy its working.