I cannot create click and move script

Hello everyone. I already watched 3 videos and none of them worked for me. I have watched one of the videos and i wrote carefully everything what i saw.
It will be my 4’th attempt and finally decided to create topic about that but it gives me error

Assets\Script\ClickToMove.cs(21,26): error CS1955: Non-invocable member ‘InputAction.enabled’ cannot be used like a method.

I have tried to change input system old to new and still same error.

And here is the code. I cannot upload it as text file because it is not allowed for new members.

using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;

public class ClickToMove : MonoBehaviour
{
    [SerializeField]
    private InputAction mouseClickAction;
    [SerializeField]
    private float playerSpeed = 10f;

    private Camera mainCamera;
    private Coroutine coroutine;
    private Vector3 targetPosition;

    private void Awake() {
        mainCamera = Camera.main;
    }

    private void OnEnable() {
        mouseClickAction.enabled();
        mouseClickAction.performed += Move;
    }
    
    private void OnDisable() {
        mouseClickAction.performed -= Move;
        mouseClickAction.Disable();
    }

    private void Move(InputAction.CallbackContext context) {
        Ray ray = mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue());
        if (Physics.Raycast(ray: ray, hitInfo: out RaycastHit hit) && hit.collider) {
            if (coroutine != null) StopCoroutine(coroutine);
            coroutine = StartCoroutine(PlayerMoveTowards(hit.point));
            targetPosition = hit.point;
        }
    }

    private IEnumerator PlayerMoveTowards(Vector3 target) {
        while (Vector3.Distance(transform.position, target) > 0.1f) {
            Vector3 destination = Vector3.MoveTowards(transform.position, target, playerSpeed * Time.deltaTime);
            transform.position = destination;
            yield return null; 
        }
    }

    private void OnDrawGizmos() {
        Gizmos.color = Color.red;
        Gizmos.DrawSphere(targetPosition, 1);
    }
}

Uploading it inside code tags, as you’ve done, is actually better. It lets others view and copy/paste the code without downloading anything.

To add code tags yourself, use:


```csharp
// your copy/pasted code here
```

Regarding your issue:

The error indicates that on line 21 of the ClickToMove script, you’re trying to use InputAction.enabled as if it were a method. It isn’t a method, it’s a property. You can verify that in Class InputAction | Input System | 1.16.0

Because you haven’t copied the script the way I mentioned above and it probably was added between tags automatically, this corresponds to the line mouseClickAction.enabled();

You probably wanted to write: mouseClickAction.Enable();

When following video tutorials, make sure your code matches what’s shown. If you get an error, the compiler usually points you to the relevant line or close to it. Use that to compare your code with the tutorial.

These kinds of errors are useful for practicing debugging. In tutorials, you know the shown code works, so any mistake is almost certainly in your own version. Carefully rechecking the tutorial will usually reveal the issue quickly.

Ah, there’s your problem. Watching videos will not teach you anything.

Two steps to tutorials and / or example code:

  1. do them perfectly, to the letter (zero typos, including punctuation and capitalization)
  2. stop and understand each step to understand what is going on.

If you go past anything that you don’t understand, then you’re just mimicking what you saw without actually learning, essentially wasting your own time. It’s only two steps. Don’t skip either step.

Step #2 is particularly critical when learning.

If you are unwilling or unable to do Step #2, just ask someone else to do the whole game for you.

For the specific error and ANY ERROR, go straight to the documentation.

You’ll see the correct spelling of the method… it is capitalized:

action.Enable();

NOTE: there is also an .enabled property (read-only). Those two things are NOT the same thing!

This is why 100% accuracy and comprehension is a requirement of programming.

Ok i learned how to post script properly and updated my message. Now i will try to understand your suggestions but i have no knowledge about coding. Just created gaming map and one of my friends learned about modelling and we want to see how it looks like if i am able to move it.

I know i cannot learn because i am currently not learning. Before i proceed i just want to see how it looks. This is why i have watched 4 videos but none of them worked. This is why i have decided create post about that.

When it comes to your messages sadly i do not understand yet but tonight i will read carefully.

I am planning to use this forums many times because i want to create my own game. I will start to learn C# but before i do that i just want to see units moving. Tonight i will read this post carefully.

Update 1: Yes it worked. Somehow it changed automatically. But still i cannot move. I will share details later (after some tests)

Ok first part solved.

What i learned: I have to read and check 100%

I do not know why but it seems visual studio automatically change while typing.

But still i cannot move.

I have a model with rigidbody, box collider, mesh collider. And of course this script (ClickToMove) as component. When i start and click somewhere in the map, nothing happens. I assume i have to “select units” first.

Additionally i have created Cube object and put same components inside of it and nothing happens again.

How do i select models? Cube or my model does not matter. I just want to see objects are moving when i clicked somewhere. After i learned how to click and move, i can set this topic as solved and continue my work.

That is absolutely the bare minimum. It is not sufficient however. See step #2 above.

Visual Studio performs “intellisense” as you work. I’ll let you google for more about that.

That means it’s time to start debugging!

You’ve gone through and doublechecked your typing, that’s GREAT! That’s the first part. Now go through and check if everything is happening the way it is expected to based on the tutorial or example code. All the code in the world is worthless if it isn’t running properly or getting the right data. Debugging is about ensuring this second part.

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

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

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

Remember with Unity the code is only a tiny fraction of the problem space. Everything asset- and scene- wise must also be set up correctly to match the associated code and its assumptions.

Does your game map have a collider? If not, the raycast won’t have anything to hit

@Kurt-Dekker Actually i am 40 years old and just started to use Game Engine. I have just created map, imported several assets and one of my friends learned modelling and created 2 models for us. I have barely learned about collision collider, box collider etc and NO IDEA about C# but i will learn. But before do that we want to see our model can walk.
About debugging, i do not know what should i debug. If you are asking about errors, here it is.

@yenwoda I even do not know what is raycast and how to configure collider for map :slight_smile:

I have 23 years old moba style game (Warcraft III map, mod) and created 70+ heroes, 280+ abilities, 100+ items and i was dreaming making it as real game. I always told myself “it is too late” but i realized i am saying it more than 10 years, and i have started. This is my story.

I am ultra beginner but i will try to learn.

Whenever you see an error, ANY error, don’t post here.

Go directly to google. Start there. If the first link makes no sense, hit the next one.

You will NEVER be the first person to see that error.

Look at tutorials for what you’re doing.

You absolutely will NEVER get anywhere measureable if the instant you get an error you start posting online. That’s simply not a recipe for success.

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.

Try this pattern for working: when you get overwhelmed, start chopping up the problem into smaller and smaller pieces.

If you’re following a tutorial, that provides a nice way to start dissecting it into its component parts.

If you’re not willing to at least attempt to understand the parts, you won’t be able to succeed.

Imphenzia: How Did I Learn To Make Games:

@Kurt-Dekker I know you are trying to help me. I am a kind of teacher who taught many things to people because i am going for the direct answer. And of course i am expecting the same. I have already watched 4 videos and searched many error messages on google and nothing changed. This is my 33’rd day and still i cannot move any object.

Clicking and moving object is extremely difficult part? If yes, how the hell “simple click and move system” based videos not worked for me? None of them? My google history includes 60+ error messages. I am tired now, gave up and decided to ask people for help.

I just need information like this “create cube, add those components, add this script and it works”

because i do not know which part am i failed. Models? objects? Project settings? Scripting? Unity version? I am just a person who start video and do everything in the video but still i cannot succeed.

I do not know where should i look at. This is why after 33 days i gave up and decided to use these forums. Before i come here and create topic i already spent countless hours within 33 days period and people told me “why you are so stubborn? why not asking people for help” because i wanted to try much more before i give up.

I just need someone just like me (i am teaching people everything i know step by step and thinking like they are idiots and believe me it works) because 33 days is too long for realizing and learning by yourself. This is why i am here. I do not know what should i do. I have failed with 4 videos and that means it changes nothing even if i watch 100+ videos that shows “how to click and move your character” because i do not know why i am failing.

Even if someone gives you a possible fix, which isn’t easy since the correct solution depends on context, it won’t help you much in programming.

Programming requires close attention to detail. As mentioned earlier:

Tutorial code is known to work, so your job is to identify what you did differently and correct it. That’s all there is to it. You need to follow the videos more carefully, there’s no reason four separate tutorials would all be wrong. In your original mistake, you wrote mouseClickAction.enabled(); instead of mouseClickAction.Enable();. You should be able to spot this on your own by checking the line the error message points to (line 21) and comparing it to the tutorial’s code.

This is a core part of programming. You will spend more time figuring out why your code doesn’t work than writing new code, no matter your level, and tutorials make it easy to practice this skill.

If you still can’t follow the tutorials, programming may not be the right fit. Accumulating more than 60 errors while following a tutorial is excessive. Some things simply aren’t suited for everyone. That’s not a problem, game development includes many disciplines: game design, narrative design, music, VFX, animation, and more. If programming isn’t for you, choose another area and collaborate with programmers who are skilled in that part of the work.

As you already know as a teacher, not everyone can do everything.

Yes not everyone can do everything but i wasn’t knew it was extremely difficult to creating empty object and moving object to the clicked area. I am not even talking about movement animation, casting skills, attacking etc etc.

4 YouTube videos about “how to click to move” not worked for me, shared with you and still we don’t know why it is not working. Probably this is why it took 33 days.

Then can you suggest more simple system for the MOBA style game? Let me work on it.

Programming is funny that way. Because 100% has to be correct (not 99.999%… that is not correct enough!), there is a nearly-infinite surface for issues to appear.

Not only that but there is no facility in the computer to read your mind and compare what you have done versus what your intention was in the first place. The computer will happily do the wrong thing ALL DAY LONG, forever into the future, if that’s what you told it. Computers are really really dumb.

The only defense is dogged determination and debugging. You have to NEVER get stopped and hung up on anything… forward motion always. If something doesn’t work, back up and retry it.

See the “Can I …?” video above. The only progress you will make will come in small single steps, and it’s VERY easy to make a wrong step, so it’s even more important to be ready to back up and identify what is happening, perhaps even retry the entire process, all the while paying attention to WHAT you did so you can stop and go back and understand WHY the tutorial told you to do it (part 2 in my first reply, message #3 above).

Ok ok forget about everything. Consider this one is my first question. Forget everything.

Hello everyone. I want to create 3d object on empty surface and i want to make it move when i click anywhere and i do not know how to do that.

I have software called as Unity and also i have Visual Studio. I have created empty map, created 3d object (cube) and now i can see cube. When i start the game i can see cube stays on the ground. But i want to make it go the place that i have clicked. But i do not know how to do that.

Is anyone can tell me?

OR

can show me in private?

OR

can show me video about that?

OR

can show me guide about that?

OR

can share the link about that in that forums?

This might look simple, but it isn’t. To implement something like this, you first need to understand the input system. After choosing one of the two available options, you need to write a script that detects clicks. Then you have to move the object to the place the user clicked. That step alone has multiple parts.

The first part is the click logic: you need code that distinguishes between clicking to select an object and clicking on a location in the map. For the first case, you must understand physics, specifically raycasts. For the second, you need to understand coordinate systems and how to transform coordinates from screen space to world space in 3D.

Even after that, you still have to instruct the object to move. And that’s assuming there are no other units or obstacles in the way. If there are, then you also need to understand pathfinding AI. Beyond that, there are different movement approaches. The two basic options are:

  1. Moving the object via its transform, this will cause problems with physics elements like collisions.
  2. Using physics based movement, this includes changing velocity, moving the rigid body directly, or applying forces. Each of these methods also has different modes depending on what you want to achieve.

These are the “simple” parts, because each piece of code has to interact correctly with the others. A small bug can turn debugging into a nightmare compared to just watching a tutorial and following along.

I’m sure I’ve forgotten several things, these are just off the top of my head and if I were to implement a system like this, I would encounter even more issues along the way.

So, regarding your questions:

I just did, but it’s far more complex than a simple script.

You can try the collaboration forum. Add the tag non-commercial-collaboration-offering if you’re not offering payment, or commercial-collaboration-offering if you are.

Searching for solutions online is an essential programming skill. What you’re asking for is very specific, so unless someone reading the topic has already followed a tutorial on this exact subject, you’ll need to search for one yourself.

Yes, as we have done multiple times now… you will need to learn and discover these parts AS YOU GO.

You cannot stop at the first error, panic and post on the forums.

You have to fix your errors and move forward.

As an example of all you will discover, I shall now write out all of the minimum parts.

NOTE: none of the parts below can be skipped.

Set up the scene:

  • launch Unity, make an empty project to work in
  • make a default scene with camera and light
  • save the scene now
  • place a Plane primitive in scene at (0,0,0)
  • adjust the camera to look down on that plane (lift it and angle it down)
  • make a Material, color it brown, drag it onto the Plane
  • go into the Tag Manager, create a Ground tag
  • apply that tag ONLY to the Plane object
  • flag only the Plane as Navigation Static
  • save the scene (necessary for the next part)
  • open the Navigation window, find the Bake tab, Bake navmesh
  • Make a blank GameObject at (0,0,0), name it Bonzo (our avatar)
    → put a NavMeshAgent on Bonzo
    → make a child Capsule primitive under Bonzo, lifted up by one ( in scene at (0,1,0))
    → remove the CapsuleCollider from Bonzo
    → make a Material, color it blue/cyan, drag it onto Bonzo
  • save the scene again

Create the script:

Make the script. It will need:

  • reference to the camera (public Camera cam;)
  • reference to Bonzo (public NavMeshAgent bonzo;)
  • definition of ground Layermask

In Update it will:

  • listen for mouse down clicks
  • when a mouse down click happens:
    → read the mouse position
    → use the camera to create a ray from that position
    → use Physics.Raycast() to cast into the scene:
    -----> specify the Ground as a LayerMask argument
    -----> specify a RaycastHit to get results from the raycast
    → if the click-raycast hits the ground:
    -----> get the point out of the RaycastHit
    -----> tell the Bonzo’s NavMeshAgent to go to the point

No parts of that can be omitted.

This is why we work one step at a time.

The Script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

// @kurtdekker... bare minimum click-to-navigate.
//
// Read full requirements here (scroll WAAAY down):
//
// https://discussions.unity.com/t/i-cannot-create-click-and-move-script/1696272
//

public class BonzoClicker : MonoBehaviour
{
	public Camera cam;

	public NavMeshAgent bonzo;

	public LayerMask GroundMask;

	void Update()
	{
		if (Input.GetMouseButtonDown(0))
		{
			Vector3 mousePosition = Input.mousePosition;

			Ray ray = cam.ScreenPointToRay(mousePosition);

			if (Physics.Raycast(ray: ray, out RaycastHit hit))
			{
				Vector3 point = hit.point;

				bonzo.SetDestination(point);
			}
		}
	}
}

Full scene setup:

BonzoClicker.unitypackage (31.2 KB)

If you fail to do Step #2 above (specifically, LEARN EVERY PART of what I have written above), you will never be able to move onto anything more. You’ll be trapped here in this same point in time.

It depends what sort-of questions you ask. Unfortunately there very-quickly comes a point where no one can just look at your code listing and tell you what the problem is. Anything but the simplest code is practically hard for outsiders to follow, and also there’s going to be context with your scene, GameObjects, and components that’s not going to be apparent to the outside observer.

“Math is hard” - Teen Talking Barbie

For the most part, the best that people will be able to do is give you pointers on how you can debug the problem yourself- but really that will be the most beneficial path for you as well- “Teach a man to fish” and all that.

I guess what I’m trying to say is that if it seems like people are reluctant to give you the answer, it’s really just because the answer is not attainable to people outside of the project.

@meredoth and @kdgalla thank you for your aid. I believe you have to realize i am new, spent 33 days only for one thing, failed and came here for help. Probably you right. But i am not experience for the understand. But finally dear Kurt gaves me what i want. Now i am able to compare my work with his and see the difference.

@Kurt-Dekker Thank you so MUCH. Tonight i will do everything step by step, then implement the same script within my game and we will see what happens next. If still i cannot move in my game, that proves there is no problem with all C# scripts and i will start to look elsewhere. I will let you know when i am done.

Yes, sorry. I had a few drinks last night and was in a “mood”. My reply was flippant and not very helpful. :flushed_face:

@kdgalla No problem my friend.

@Kurt-Dekker Here is what i did.

I want to go step by step with every detail.

  1. New project > Universal 3D > Create project (it took 2-3 minutes to load)
  2. It comes wity default scene (saved)
  3. Placed Plane Primitive (i did not know, googled it)
    Right click > 3D object > Plane
  4. Camera does not matter at this point (and i do not know how to set it properly, i skipped)
  5. Right click > 3D object > Cube (placed on the ground)
  6. Clicked on the Plane > Tag > Add tag > Clicked + > Typed Ground and saved.
    Returned Inspector and selected Tag > Ground
  7. I can see box called Static but unticked. I have ticked it.
  8. Clicked on terrain, added NavMesh Surface component and clicked on Bake. And also already selected Ground from the top right corner (Layer > Ground)
  9. Created object and named it as Bonzo and added NavMeshAgent on it.
  10. Created child capsule primitive (right clicked, create 3d object, create cube, named it as Bonzo2, clicked and hovered on Bonzo and now i am able to see it is under the Bonzo at the Hierarchy window. By the way still i do not understand why we are created this thing.
  11. WARNING: You told me the remove capsule collider but it does not have. I have skipped this step
  12. STUCKED: Before i proceed to Script, i do not understand these

Make the script. It will need:

  • reference to the camera (public Camera cam;)

  • reference to Bonzo (public NavMeshAgent bonzo;)

  • definition of ground Layermask

I have default camera named Main Camera. Should i name it cam?

You said refence to Bonzo. How can i use this reference thing?

You said definition of ground Layermask. How can i use this reference thing?

Before go further i believe it is best to go step by step because i want to make sure about previous steps.

Now you are able to see every step that i take.

Current progress: Stucked and waiting for help.