- Home /
How can i assign prefab to transform without drag & drop from project to inspector
Hey Everyone I need help on assigning a prefab to either a variable or transform so, when I press space bar the prefab will show up on the screen. I am coding in C#, and I used the References.load() and it doesn't work I always get an need a cast Error. I do not know why using scripts in Javascript work with the documentation but in C# you always need something extra.
Here is my code:
using UnityEngine;
using System.Collections;
public class player_script : MonoBehaviour {
int health = 100;
int speed = 5;
GameObject collided_with;
Transform laser_prefab;
// Use this for initialization
void Start () {
GameObject instance = Instantiate(Resources.Load("Lazer"));
}
// Update is called once per frame
void Update ()
{
if (Input.GetAxis("Horizontal") > 0 )
{
if (collided_with != null)
{
if (collided_with.tag == "Left")
{
return;
}
}
transform.Translate(new Vector3(1 * speed * Time.deltaTime, 0, 0));
}
if (Input.GetAxis("Horizontal") < 0 )
{
if (collided_with != null)
{
if (collided_with.tag == "Right")
{
return;
}
}
transform.Translate(new Vector3(-1 * speed * Time.deltaTime, 0, 0));
}
if (laser_prefab != null)
{
if (Input.GetAxis("FireLazer") != 0)
{
Instantiate(laser_prefab, new Vector3(transform.position.x, transform.position.y + 1), Quaternion.identity);
}
}
}
void OnCollisionEnter(Collision col)
{
collided_with = col.gameObject;
}
void OnCollisionExit(Collision col)
{
collided_with = null;
}
}
Here is the error I get from: GameObject instance = Instantiate(Resources.Load("Lazer"));
i says cannot convert type, your missing a type cast?, and it bothers me that the Documentation just translates the JS code to C# although not really go into the perspective of doing everything to make sure it works, like for example to use Vector3 You have to place new infront of it. Unity Documentation just uses the Vector3 without anything behind it.
but, anyways is there an easier way to assign prefabs and to make them show up, without dragging or dropping, I cannot seem to find the Transform, or my variable in the inspector, via it isn't showing up when I click on my script.
Answer by robertbu · May 31, 2013 at 04:06 AM
To fix the error change to:
GameObject instance = Instantiate(Resources.Load("Lazer")) as GameObject;
As a true prefab, your approach is about as simple as it gets. Note Instantiate() will take a scene object not just a prefab. So if what you want to Instantiate() exists in the scene somewhere, you can use GameObject.Find() or GameObject.FindWithTag() to find a specific game object to instantiate.
Thanks your the best, I'll Research more into those functions
Your answer
![](https://koobas.hobune.stream/wayback/20220613103239im_/https://answers.unity.com/themes/thub/images/avi.jpg)