Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Call a function of an Instantiated object's script

Discussion in 'Scripting' started by Eegxeta, Aug 16, 2016.

  1. Eegxeta

    Eegxeta

    Joined:
    Jun 23, 2016
    Posts:
    21
    I'm creating program that procedurally generates a galaxy. In this program I'm trying to get the calculated temperature of a planet, but in order to do so I need the luminosity of the star it orbits. I haven't been able to figure out how to access information from one game object's script in another's. Is there a way to call a function from the script of an object you have instantiated?
     
    Last edited: Aug 16, 2016
  2. DroidifyDevs

    DroidifyDevs

    Joined:
    Jun 24, 2015
    Posts:
    1,724
    You need to access the class of another script like this:

    public ClassYouWantToFind CallItWhatYouWant;

    Then, in the Unity inspector, drag the gameobject with that class you want into your script where you want it. Then for example, if ClassYouWantToFind has public int UseMePlease, you'll use CallItWhatYouWant.UseMePlease to access it!
     
  3. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    That would work if we weren't instantiating the object at runtime.

    Eegxeta, try something like this:
    Code (CSharp):
    1. GameObject newObj = Instantiate( ... ) as GameObject;
    2. YourScript script = newObj.GetComponent<YourScript>();
    3. script.YourPublicFunction();
    Just fill in the instantiate function, and replace "YourScript" and "YourPublicFunction"
     
  4. DroidifyDevs

    DroidifyDevs

    Joined:
    Jun 24, 2015
    Posts:
    1,724
    Good answer. In case that code wouldn't work, you could always do it like a noob and use GameObject.FindWithTag but your method is probably better.
     
  5. Eegxeta

    Eegxeta

    Joined:
    Jun 23, 2016
    Posts:
    21
    Well I changed the code using what you gave me and now Unity locks up when I hit the play button, but thanks for the help I just need to figure out how to fix the end conditions for the loop I need to run the recursive equation needed to find the Eccentric anomaly of a planet's orbit.
     
    Last edited: Aug 16, 2016
  6. DroidifyDevs

    DroidifyDevs

    Joined:
    Jun 24, 2015
    Posts:
    1,724
    Can you post the code you're using? Sounds like an infinite loop to me
     
    Kiwasi likes this.
  7. Eegxeta

    Eegxeta

    Joined:
    Jun 23, 2016
    Posts:
    21
    It is a loop for a recursive equation. So it is supposed to run until it gets the same answer twice.

    Code (CSharp):
    1. while (E != c)
    2.         {
    3.             E = c;
    4.             c = M - e * Mathf.Sin((float)E);
    5.         }
    I originally wrote this stuff in python in which it worked, but even still.

    Here is the original loop.

    Code (Python):
    1. while valid == False:
    2.             E, c = self.run(E, M, e)
    3.             if E == c:
    4.                 valid = True
    5.  
    6. def run(self, E, M, e):
    7.         c = M + e * math.sin(E)
    8.  
    9.         return c, E
    Being able to return and assign multiple things at once is so useful.

    I've already thought of a number of ways to bypass the problem but I'd still like to hear your thoughts. Although figuring out why it doesn't work as it is would result is the best code.

    *edit*
    I figured it out.

    *edit*
    Nope nevermind.
     
    Last edited: Aug 17, 2016
  8. Errorsatz

    Errorsatz

    Joined:
    Aug 8, 2012
    Posts:
    555
    In the Python, c = M + e * sin(E); in the C# it's M - e * sin(E)
    Is that an intentional change?

    Also, you're setting E = c before the calculation instead of after it, which could change things. I think the closest to the python would be:
    Code (csharp):
    1. while (E != c) {
    2.    c = E;
    3.    E = M + e * Mathf.Sin((float)E);
    4. }
    ... probably. Change your variable names to something useful! I can't even tell if the switch in the order of E,c / c,E in the python part is intentional or not, because I have no idea what these letters are representing.
     
    Last edited: Aug 17, 2016
    DroidifyDevs likes this.
  9. Eegxeta

    Eegxeta

    Joined:
    Jun 23, 2016
    Posts:
    21
    No thanks for catching that.

    *edit*

    Ok from reviewing my Python code the equation needs to run a few hundred times before it starts bouncing back and forth between two numbers.
     
    Last edited: Aug 17, 2016
  10. Eegxeta

    Eegxeta

    Joined:
    Jun 23, 2016
    Posts:
    21
    So thanks to Errorsatz I caught a mistake I had made in the python version and was able to fix it. Here is the working loop.

    Code (Python):
    1. while valid == False:
    2.             k = E
    3.             E, c = self.run(E, M, e)
    4.             if c == k:
    5.                 valid = True
    6.  
    7. def run(self, E, M, e):
    8.         c = M + e * math.sin(E)
    9.  
    10.         return c, E
    Now to figure out how to write this in Csharp.
     
  11. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    I'd consider using Mathf.Aproximately. float equality comparisons are notorious for never quite converging.
     
  12. Eegxeta

    Eegxeta

    Joined:
    Jun 23, 2016
    Posts:
    21
    Thanks.
     
  13. mymi_rc_unity

    mymi_rc_unity

    Joined:
    Mar 8, 2022
    Posts:
    1
    Thanks a lot ♥
     
  14. Cosmology27

    Cosmology27

    Joined:
    Jul 11, 2019
    Posts:
    61
    This is looking exactly like what I need, but I'm running into a problem which is most likely just my ignorance in coding. When you say "YourScript script = newObj....." I'm getting a error at "YourScript". If I type the name of my script, it doesn't have a reference to it, so it just looks like I'm making random junk up out of context. What exactly is happening there? I'm sure it's just a way of making variables I don't get or something. Here's my attempt at it. BloodSpurtObj is the prefab I have assigned, and BloodSquirt is the name of the script on that prefab. Everything I do is saying that the script doesn't exist within this context.
    Code (CSharp):
    1. GameObject NewBloodSpurt = Instantiate(BloodSpurtObj, hit.point, this.transform.rotation) as GameObject;
    2. BloodSquirt ScriptFromObj = NewBloodSpurt.GetComponent<BloodSquirt>();
    3. ScriptFromObj.MakeBloodSquirt(hit.transform.tag);
     
  15. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,370
    This is not a useful statement. Neither is necro-posting to 2016 threads to fix your simple typing mistakes.

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.

    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.
     
  16. Cosmology27

    Cosmology27

    Joined:
    Jul 11, 2019
    Posts:
    61
    Thanks! And sorry for the necro. So the error like I said at the bottom is saying it's out of context. So the thing doesn't exist in the current context. I have googled it, and obviously this is quite a common problem, and mine is a bit more of a specific case of the error. I have found a couple of places that have dealt with it, and the fixes aren't working for me, so I'm guessing there's some other problem I'm not realizing. I asked a coder friend of mine too and he said what I'm doing "should" work, so he was confused as well.
    My issue with the fix given above that seems to have worked for others is the line
    Code (CSharp):
    1. YourScript script = newObj.GetComponent<YourScript>();
    Now obviously I'm quite ignorant in coding, so it's definitely something I just don't get, but this seems really odd to me. I forget how to properly word it, but where you basically invent your own variable type with it's own parameters that you've set. That seems to be what's happening here, and then they're naming this new example of the new variable "script", but then the values reference the variable type just created, which makes no sense to me. Either way, when I try to create a new variable type (again, I know I'm probably not saying that correctly), I'm getting the error that says
    "The type or namespace name 'YourScript' could not be found (are you missing a using directive or an assembly reference?)" And again this is a pretty common error, I've seen it a ton in my own stuff, but there's something specific about creating that new type of variable there.
    Again, sorry for my own ignorance here, and sorry for the necro. I necrod it because it's dealing with the exact thing I want to address, and the fix isn't working for me.
     
  17. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,370
    Anytime you see something like this it is a placeholder.

    Same with something like ExampleClass or MyClass or YourClass, etc.

    It's like saying "Go eat dinner now."

    I'm not telling to find an item called "dinner" and put it in your mouth.

    I am telling you to go find an appropriate food and eat it for your dinner meal.

    If you don't understand this:

    Then go back to some very basic tutorials on how Unity works. This is so utterly totally fundamentally critical to operating in the Unity environment that it will hinder and impair you forever and more until you absolutely understand what it means.

    Not understanding the above would be like not knowing what to do with your dinner in order to consume it. It's that fundamental.

    And in any case, let's ALL STOP POSTING TO OLD THREADS. Start your own new thread please! It's only abiding by forum rules after all.

    Get with some coding tutorials for Unity. There's thousands to choose from.

    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.
    BE PERFECT IN EVERYTHING YOU DO HERE!!

    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

    Finally, when you have errors... DO NOT POST HERE! Go fix your error. Here is how:

    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.

    Imphenzia / imphenzia - super-basic Unity tutorial:



    Jason Weimann:



    Brackeys super-basic Unity Tutorial series:



    Sebastian Lague Intro to Game Development with Unity and C#:



    Imphenzia: How Did I Learn To Make Games:

     
    Cosmology27 likes this.