Issues with making a moving/sine graph.

Site: Building a Graph (catlikecoding.com)

using UnityEngine;
using UnityEngine.UIElements;

public class Graph : MonoBehaviour {

    [SerializeField]
    Transform pointPrefab;

    [SerializeField, Range(10, 100)]
    int resolution = 10;

    Transform[] points;

    void Awake() {
        float step = 2f / resolution;
        var position = Vector3.zero;
        var scale = Vector3.one * step;
        points = new Transform[resolution];
        for (int i = 0; i < points.Length; i++) {
            Transform point = points[i] = Instantiate(pointPrefab);
            position.x = (i + 0.5f) * step - 1f;
            point.localPosition = position;
            point.localScale = scale;
            point.SetParent(transform, false);
    }
   
    void Update () {
            float time = Time.time;
            for (int i = 0; i < points.Length; i++) {
                Transform point = points[i];
                Vector3 position = point.localPosition;
                position.y = Mathf.Sin(Mathf.PI * (position.x + time));
                point.localPosition = position;
        }
    }
           
    }
}

In Section 4.0 to 4.3 of the page, I was trying to create a sine wave, but when I tried to run my code, its just a straight line.

So please investigate this issue and ask for information if you need help on helping me.

Even better, here is how YOU can investigate your issue and hopefully fix it!!!

Time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

If you are looking for how to attach an actual debugger to Unity: https://docs.unity3d.com/2021.1/Documentation/Manual/ManagedCodeDebugging.html

ā€œWhen in doubt, print it out!ā„¢ā€ - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

1 Like

I would prefer if you could actually help directly rather than copy & paste what you said last time.

Oh, also, Debug.Log() itself causes an error because it takes 0 arguments.

We would prefer that you follow the easy steps above to learn how to debug.

If you have a better way to fix programs, by all means use it.

The purpose of this forum is to assist people who are ready to learn by doing, and who are unafraid to get their hands dirty learning how to code, particularly in the context of Unity3D.

This assumes you have at least written and studied some code and have run into some kind of issue.

If you haven’t even started yet, go check out some Youtube videos for whatever game design you have in mind. There are already many examples of the individual parts and concepts involved, as there is nothing truly new under the sun.

If you just want someone to do it for you, you need go to one of these places:

https://livehelp.unity.com/?keywords=&page=1&searchTypes=lessons

Remember this is YOUR game, not ours. We have our own games we’re working on.

When I write Debug.Log() it is understood by even the most junior software engineer that I refer to ā€œuse this methodā€ not ā€œtype these symbols verbatim and complain about syntax errors.ā€

It’s up to YOU to go look at what Debug.Log() does and how to use it, if it is not obvious to you. That’s what the documentation is for.

Perhaps you need to set this ambitious graphing program aside and review some basic C# programming tutorials.

I am not a college graduate; I am just someone who is trying to learn unity through these tutorials from that site.

Its catlikecoding!! It reviews code and shows what it means while learning how to create stuff. Also, creating a graph isn’t ambitious, that is part of the beginner’s tutorial in that site. :facepalm:

Again, if you are unwilling to write Debug.Log() output to show the actual values of position.x and time and see if they are reasonable, I’m not sure what else anyone can do.

This also assumes you follow the tutorial accurately, and apparently this was not the case.

Your code does NOT match what was in the tutorial: you have placed Update() within Awake()'s block.

Don’t do that. Unity can’t ā€œseeā€ Update() if it is inside of Awake().

Don’t monkey with the indentation. If Visual Studio is fighting you on indentation then you are typing the program incorrectly. Indentation doesn’t matter in C#. Open/close braces do.

Move your entire Update() method out of the Awake() method.

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, don’t post here… just go fix your errors! Here’s how:

You can fix your own typing mistakes. Here’s 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.

Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly? Are you structuring the syntax correctly? Look for examples!

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.

using UnityEngine;
using UnityEngine.UIElements;
  
public class Graph : MonoBehaviour 
{
  
    [SerializeField]
    Transform pointPrefab;
  
    [SerializeField, Range(10, 100)]
    int resolution = 10;
  
    Transform[] points;
  
    void Awake()
    {
        float step = 2f / resolution;
        var position = Vector3.zero;
        var scale = Vector3.one * step;
        points = new Transform[resolution];
        for (int i = 0; i < points.Length; i++)
        {
            Transform point = points[i] = Instantiate(pointPrefab);
            position.x = (i + 0.5f) * step - 1f;
            point.localPosition = position;
            point.localScale = scale;
            point.SetParent(transform, false);
        }
    }
  
    void Update ()
    {
        float time = Time.time;
        for (int i = 0; i < points.Length; i++)
        {
            Transform point = points[i];
            Vector3 position = point.localPosition;
            position.y = Mathf.Sin(Mathf.PI * (position.x + time));
            point.localPosition = position;
        }
    }
}

Wow good spot.

This is why I dislike this ā€˜same-line leading brace’ (not sure what it’s called) coding style some folks use.

Were they laid out normally it would be plainly clear that something is amiss:

public class Graph : MonoBehaviour
{
    [SerializeField]
    Transform pointPrefab;

    [SerializeField, Range(10, 100)]
    int resolution = 10;

    Transform[] points;

    void Awake()
    {
        float step = 2f / resolution;
        var position = Vector3.zero;
        var scale = Vector3.one * step;
        points = new Transform[resolution];
        for (int i = 0; i < points.Length; i++)
        {
            Transform point = points[i] = Instantiate(pointPrefab);
            position.x = (i + 0.5f) * step - 1f;
            point.localPosition = position;
            point.localScale = scale;
            point.SetParent(transform, false);
        }
 
        void Update ()
        {
                float time = Time.time;
                for (int i = 0; i < points.Length; i++)
                {
                    Transform point = points[i];
                    Vector3 position = point.localPosition;
                    position.y = Mathf.Sin(Mathf.PI * (position.x + time));
                    point.localPosition = position;
                }
        }       
    }
}
2 Likes

See? That wasn’t so hard now, wasn’t it? Help you to help me in the first place.

It was the actual first line of what I told you to check. I’ll copy it here for you since apparently you didn’t read it:

You could have solved all of this yourself based on my first post.

1 Like

You don’t really learn anything if we just point out the errors in your code.

Coding is half being a machine, half problem solving. It’s more in your interest to learn how to solve your own problems that you will face on a daily basis (usually dozens of times in any given coding session) then having your hand held each step of the way.

Like Kurt said you could’ve figured out the code wasn’t running if you used Debug.Log like initially suggested instead of complaining. Then you would’ve easily solved the problem yourself at that point, or at least had a lead as to why.

Not trying to be rude, but you won’t get far with coding if you don’t learn the crucial art of debugging.

2 Likes

Go easy on the new fella, guys. Debug.Log wouldn’t have helped at all in this case.

It would have. If they put one in the (nested) Update method, they would’ve learnt it’s not running. First step with debugging is to always test if the code is running at all.

Once they know that the code isn’t running, they can then work out why it isn’t running.

I’m sure we all do this on a daily basis when coding.

1 Like

Yeah perhaps. It’s a tricky problem for somebody new as the code doesn’t show any errors in the console. And I agree with you on the braces, that weird bracing format that some coders use is awful.

The manual has all this information: Unity - Manual: Console Window

Click on the bar across the bottom of the editor and if there’s anything worth seeing then it’ll open up the console. The bar/console in your screenshot is showing 0.1269814

Yes, the second tab in the lower left window of your screenshot, the one marked … ā€œConsole.ā€ :slight_smile:

You should think of that console as a firehose of potential data that you can blast back into your brain to help you track down problems.

The console is dead-easy to access, dead-easy to extend functionality (simply by adding more logging), and no matter what other tools (Debuggers, whatever) you have handy, the console logger can give you every conceivable script-land piece of data you can dream of.

It’s that powerful. Live it, love it, write to it frequently and verbosely, raise your eyebrows when something in it mismatches your expectations.

It’s like a murder mystery! Aha, the Candlestick is missing! It must be Professor Plum in the Console Window!

2 Likes