- Home /
creating reference via script
What is the code/script equivalent of dragging an item to a slot in screen view? For example, we can manually set to use gravity for a rigidbody, but we also can set this in code:
rigidbody.useGravity = true;
We can create a GameObject in our script and then drag and drop myItem to the new slot manually in the scene view. I would like to ask you how to code this “drag&drop”.
===edited on 13. march 2014 ===== here goes: I have about 20 spell prefabs in my "spells" folder.
This is my variable to which I can assign one of my 20 prefabs from assets, in order to play a specific animation.
public GameObject _spell;
I would like to assign via script a certain animation. For example, if my player picks up a "spell_Fire" PickUp, I would like Unity to dynamically assign the fire animation prefab to my _spell variable.
I would assign the spell object to the pick up object and then while hitting the pick up you pass that reference to the player.
Answer by Spoink · Feb 26, 2014 at 01:05 PM
I'm not really sure what you mean with "dragging an item to a slot" But there are two "slots" I can think of.
Either you have an unassigned object
public GameObject MyObject
this will show up as MyObject [None (GameObject)] in the inspector.
To assign an object to this variable, you just have to do normal variable assigning
void Awake()
{ this.MyObject = GameObject.Find("ObjectToAssign"); }
The second "slot" I can think of is if you want to assign a component to your object. Adding a rigidbody, box collider or a script.
To do this you use the AddComponent-function.
gameObject.AddComponent<BoxCollider>();
"doesn't work" doesn't tell much what does not work. You want to know the code but he already told you what you are after. The only part missing is if you are after dragging a script, it would then be:
Type t = GetComponent<Type>();
Answer by pcaston2 · Oct 11, 2014 at 03:45 AM
To elaborate on the solution I used, first I created an abstract class that inherits MonoBehaviour for all my types. (Hull, Engine, etc.). Within the abstract class I specified the sub-components (both a GameObject for the mesh and a Transform for the mount point) and a method to add a new one. All my meshes are in Resources folders and I simply initialize them using the Resources.Load() method, and pass the name. From each GameObject I can get the script by saying Hull.engine.GetComponent(typeof(Engine)) or build a property that accesses it for compact code.
I was able to assemble many components using this, they are modular, but each one needs an script that inherits from the abstract class in order to specify the mount points. I suppose I could tag the mount points and find them dynamically but this works just as well.
Your answer
![](https://koobas.hobune.stream/wayback/20220613134807im_/https://answers.unity.com/themes/thub/images/avi.jpg)