how to call a function with a gameobject as a argument
I am currently having problems using a gameobject as an argument in a function.
Here is how I am trying to call the held function from another script.
Backpack.Held(0, gameObject);
below is the function in the Backpack script:
public void Held(int a, GameObject b) { }
I have tried setting the game object into a variable which did not work. I don't have to use this method to pass the game object.
for reference my situation is as follows: I pick up one of many object which has the same script, when picked up I must let another(lets say it is the main) script know which gameobject has been picked up.
I suppose I could create an empty gameobject in the main script and set it as the 'pick up's game object in the pick up script. however I would like to know if I could achieve this using my first method,(and if the second method would work)
all help is appreciated thanks
Have you tried passing the gameobject by reference ?
Yes, you can pass a game object as a parameter, and your sample code looks like the correcct way for doing that. What exact problems are you having? What "didn't work"?
it did not compile, the message i received was as folows: error CS0120: An object reference is required to access non-static member.
this seems related to what @Hellium has said however i iam unsure of how to change it
Going by the error you mentioned in the comments, you can't call it like that. Unless you have an instance of the BackPack class, you can't call a member function. It should work if you change that method to public static void, but this may change your intended functionality.
Answer by Hellium · May 27, 2016 at 07:13 AM
@TreyH seems to be right, I haven't seen the way you call the function.
You need an instance of the Backpack class to call the Held
function since it's not a static method of the class.
If the Backpack class inherits from MonoBehaviour, you must get the component / find the object holding the script :
GetComponent<BackPack>().Held( 0, yourGameObject ) ; // If the component is on the same object as your current script
FindObjectOfType<BackPack>().Held( 0, yourGameObject ) ; // If the component is on an other gameobject
If the backpack does not inherit from MonoBehaviour :
Backpack pack = new Backpack();
pack.Held( 0, yourGameObject);
Your answer
Follow this Question
Related Questions
checking if gameobject exists 1 Answer
How to Serialize or Save a List of GameObjects 1 Answer
Spawn objects in a row with same spacing 0 Answers
How to change the shape of gameObjects 2 Answers
Accessing values on a gameobject 1 Answer