This question already has answers here:
Moving an object with vector3.MoveTowards
(2 answers)
Closed 4 years ago.
I have a cube that I want to always be moving towards my player. I've tried several solutions over the course of a few hours, but none of them have worked. My current script looks like this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fol : MonoBehaviour {
// Use this for initialization
void Start () {
}
public GameObject Player;
// Update is called once per frame
void Update ()
{
Vector3.MoveTowards(Player.transform.position.x, Player.transform.position.y, Player.transform.position.z, 1);
}
}
This script is a child of the object that I want to move towards my player.
Nothing has ever compiled. The only error for this script is:
Assets/fol.cs(16,11): error CS1501: No overload for method MoveTowards takes 4 arguments
So, once I remove the 1 it ends up with:
Assets/fol.cs(16,11): error CS1502: The best overloaded method match for UnityEngine.Vector3.MoveTowards(UnityEngine.Vector3, UnityEngine.Vector3, float)' has some invalid arguments
and
Assets/fol.cs(16,49): error CS1503: Argument #1 cannot convert float expression to type UnityEngine.Vector3
In your MoveTowards the first position given should be the position of the object you need to move, then the second should be the position of the goal, with the third argument being the movement increment. As #Ruzihm suggests this is a duplicate of Moving an object with Vector3 and you'll find a great info to resolve this there. Also check out the unity API.
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
In Unity (C#), why am I getting a NullReferenceException and how do I fix it? [duplicate]
(1 answer)
Closed 1 year ago.
I have an enemy AI script working that basically follows my player. Right now I have a "public GameObject player" that I have to assign manually by dragging my player prefab onto the slot. But I want to have a lot of enemies in the scene, so I don't want to have to do this manually for each one. How Can I give the EnemyController script a default player to follow?
I have a PlayerManager which I use to pass the position of my player to the enemy with:
public class EnemyController : MonoBehaviour
{
Transform target;
// Start is called before the first frame update
void Start()
{
target = PlayerManager.instance.player.transform;
}
That part works fine. So my thinking was, just make a public variable for the player like this:
public GameObject player = PlayerManager.instance.player;
But that didn't work. I got this error: "NullReferenceException: Object reference not set to an instance of an object"
Thank you so much for any help you can provide!
With public GameObject player = PlayerManager.instance.player; your field is initialized before the call of EnemyController's constructor, and you provided no control over the value / definition state of PlayerManager.instance.player (PlayerManager or instance or player which can be null and is null in your case). So it's "too early" to use it.
Instead, you can use the event playerJoinedEvent in the PlayerInputManager to assign the enemy to the played which just joined with an event handler, which checks that PlayerManager and instance and player are not null and then assign the player to the target.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I make a game in C# under Unity and I have a problem with the code for attack.
I've already tried to put this code in a void in the enemy script.
Enemy code :
public int Life = 5;
public int Speed = 100;
Player attack code :
// Use for player attack
public void Attack () {
if (Input.GetKeyDown("space")) {
EnemyD.Life = EnemyD.Life - 1;
}
}
// Use for Auto Attack
public void AutoAttack () {
EnemyD.Life = EnemyD.Life - 1;
}
Unity return this error :
error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement.
Thank you for your help, Jason.
If all enemies or group of enemies will have the same script, then you could call a particular script by grabbing whichever enemy was hit.
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Monster"))
{
collision.gameObject.GetComponent<EnemyD>().Life -= 1;
}
}
So if you have two enemies and you've attacked the first one, only on him will be applied this action.
Try to put scripts with proper Class name, I guess your enemy script is named EnemyD.
Let's come to point - your player is trying to access member without an instance, so it is a error.
If you try to access them without instance you have to put static before members , which means Of the class , Not of an instance.
Normally there is so many enemy, we don't use static, instead use the approach of Nikola G. from here [Posted as answer in this question].
Some links you might find helpful :
Static Variable
Class Variable
This question already has answers here:
Accessing a variable from another script C# [duplicate]
(3 answers)
Closed 6 years ago.
I have 2 c# scripts in my game. On of them is in my "main player object" and the other script is in "my main camera". I want to declare a float variable in the script of my main player, and in every game second i want to record the x position of my player in that variable and at the same time passing this value to the my main camera's script and assigning this value into the x position of my main camera in every game second. How can I pass a variable to a script from another one ? Or how can i create a variable which can be used by any script in my game ?
There's an answer here that explains this problem in great detail, but the simplest way that is included in that answer would be to do something like the following:
public class Speed: MonoBehaviour
public float speed;
// maybe you want restrict this to have read access, then you should use a property instead
And then in other scripts:
GameObject gameObject = GameObject.Find ("Some object");
Speed theSpeed = gameObject.GetComponent <Speed> ();
float mySpeed= theSpeed.speed;
(I know this question has been asked, but none of them work for me)
In my script, i have an array which is out of scope (which is strange because i'm following a tutorial which works). Can anyone see why the array is not in scope?
Code:
using UnityEngine;
using System.Collections;
public class Patrol : MonoBehaviour
{
public Transform[] PartolPoints;
void Start ()
{
transform.position = PatrolPoints[0].position;
}
// Update is called once per frame
void Update ()
{
}
}
Are you getting the array at runtime?
If so, make sure you initialize the array in the Inspector by dragging your patrolpoint GameObjects into the array, or via Code by searching for your patrol points in the start() function.
Otherwise, if you have initialized your array correctly then you are getting out of the ordinary error and i recommend reinstalling the most recent release.
That code does work correctly, i confirmed it running the same version of unity on my side.
I'm fairly new to C#(basically first time using, having to script for this project), I'm trying to teleport (from off screen to on) an object in my game(i'm using a cube for a simple object, in which I will use inkscape to create a 'better' object in its place when it works)will add cube2 later, just focusing on getting this working.
The aim is to teleport an object to where to my 'Bumber' prefab (the floor), based upon the player clicking a position on the 'Bumber' and spawn where the mouse position was on that 'Bumber' and if not on the 'Bumber' don't spawn at all(haven't go to bumber check yet), which will trigger an event, causing the player to lose.
When I was playing the game before, when I clicked, the cube would only despawn and then throw an error at me and not spawn in at the cursors position
I have my 'cube' prefab (dragged from hierarchy into Resources folder, which has the spawn script component). When I go back into unity, I get the error:
(32, 37) the name 'cube' doesn't exist in current context
(32,25) The best overloaded method match for `UnityEngine.Object.Instantiate(UnityEngine.Object, UnityEngine.Vector3, UnityEngine.Quaternion)' has some invalid arguments
(32, 25) Argument #1' cannot convertobject' expression to type `UnityEngine.Object'
I've tried for hours to fix this script, looking at unity database and to no avail.
using UnityEngine;
using System.Collections;
public class Spawn : MonoBehaviour {
public int trapCount;
void Start ()
{
trapCount = 0;
GameObject cube =(GameObject)Instantiate((GameObject)Resources.Load("cube"));
}
void Update ()
{
if (Input.GetMouseButtonDown (0))
{
Spawner ();
trapCount++;
}
}
void Spawner()
{
Vector3 mousePosition = Input.mousePosition;
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if(trapCount == 0)
{
Instantiate(cube, transform.position, Quaternion.identity); //getting error here, I don't care about rotation value, don't want to rotate at all, but doesn't like it, if it doesn't have anything there.
}
else if (trapCount >= 1)
{
Debug.Log("Trap limit reached!");
}
}
}
C# please, also, if you could, explain what you're doing, thank you kindly!
Always (well, almost always) believe what the error messages tell you.
(32, 37) the name 'cube' doesn't exist in current context
You get this for the line
Instantiate(cube, transform.position, Quaternion.identity);
At that point there is no cube anywhere within the scope of the method. You have your
GameObject cube =(GameObject)Instantiate((GameObject)Resources.Load("cube"));
in your Start() method, but it only exist within that method. It's not a member of the class for example. Making it a member would solve that problem.
And that is more than likely also the cause of the subsequent errors. If it doesn't know what a cube is, it has no idea what to do with it as an argument of Instantiate().
If you're entirely new to C# the biggest favour you could do yourself is to pick up a good book. Unity will allow you to get pretty far by hacking away at it, but there will be a point where there's simply no substitute for learning the language. It will help you tremendously.
Good luck.