public class Scroll : MonoBehaviour {
public float speed = 0.5f;
void Update()
{
Vector2 offset = new Vector2(0, Time.time * speed);
renderer.material.mainTextureOffset = offset;
}
i didn't understand where the problem is, but it is supposed to be in the renderer.material part.
I have put this code in a Quad to try and make it my background.
edit: error messages :
- Assets/Scroll.cs(12,8): error CS0619: UnityEngine.Component.renderer' is obsolete:Property renderer has been deprecated. Use GetComponent() instead. (UnityUpgradable)'
- Assets/Scroll.cs(12,17): error CS1061: Type UnityEngine.Component' does not contain a definition formaterial' and no extension method material' of typeUnityEngine.Component' could be found (are you missing a using directive or an assembly reference?)
- nable to parse file Assets/Game scene.unity.meta: [Control characters are not allowed] at line 0
You can no longer access renderer that is inherited from MonoBehaviour directly. You must use GetComponent to get the Renderer. The-same thing applies to other components such as Rigidbody and AudioSource.
Renderer myRenderer;
public float speed = 0.5f;
void Start()
{
myRenderer = GetComponent<Renderer>();
}
// Update is called once per frame
void Update()
{
Vector2 offset = new Vector2(0, Time.time * speed);
myRenderer.material.mainTextureOffset = offset;
}
Of-course, GetComponent<Renderer>().material.mainTextureOffset = offset; could have worked too but it is better to cache it like I did in the first script.
Related
Got 2 errors from 1 script and dont know whats happening.
If anyone can help that would be great.
Error is in the title and the other one is the same except instead of 'Start' its 'Update'
Thanks for reading!!
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float health = 50f;
private Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
Vector3 direction = player.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
float y = Quaternion.identity.eulerAngles.y;
float z = Quaternion.identity.eulerAngles.z;
rb.rotation = Quaternion.Euler(angle, y, z);
}
}
Using the override operator should get rid of the compiler errors, but I'm not a Unity dev so I'm not sure if Unity will treat your class in the correct way. Here's how you would do it:
override void Start()
{
...
}
// Update is called once per frame
override void Update()
{
...
}
You can read more about the override operator here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/override
I also found this article and it declares Start as an IEnumerator rather than a void so that may fix it too.
I'm writing a code of moving a object to random places.
I made a function which decides the random coordinates and returns it.
However, I think the function and is not connected together.
This is what I tried...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed;
Vector3 target;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 target = random(target);
transform.position = Vector3.MoveTowards(transform.position, target, Time.deltaTime * speed);
}
Vector3 random(Vector3 target)
{
float min = -100.0f;
float max = 100.0f;
float randomX = Random.Range(min, max);
float randomZ = Random.Range(min, max);
Vector3 target = new Vector3(randomX, 10.0f, randomZ);
return target;
}
}
And this is the error message I got.
Assets\Movement.cs(31,17): error CS0136: A local or parameter named 'target' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
How can I fix this?
The problem is you define a new target variable inside random method. You have defined it as argument in method body before. Change one of them.
It is not really a problem with unity but with compiler.
Inside the random(Vector3 target) and void Update() methods you are defining new "target" variables like this:
Vector3 target
so the compiler is telling you that this is not allowed. If you want to update the target variable then remove the "Vector3" infront or choose a new name.
It is not clear how this function is meant to work but I think it is good to declare the target on start or declare it public so you can assign a start position to it.
I think what you want is something like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed;
// OPTIONAL: declare public so the editor will let you set a position
public Vector3 target;
// Start is called before the first frame update
void Start()
{
// OPTIONAL: you can set a start position
target = Vector3.zero;
}
// Update is called once per frame
void Update()
{
target = random(target);
transform.position = Vector3.MoveTowards(transform.position, target, Time.deltaTime * speed);
}
Vector3 random(Vector3 par)
{
float min = -100.0f;
float max = 100.0f;
float randomX = Random.Range(min, max);
float randomZ = Random.Range(min, max);
return new Vector3(randomX, 10.0f, randomZ);
}
EDIT: You do not really need a parameter to the "random" function now. So maybe you can remove it
The reason you are getting this error is because you have already declared Vector3 target as a class member outside of the random and update methods.
If you are coming from a language like JavaScript, you can do it by declaring the same var variable name inside an inner scope but in C# it's not possible.
This question already has an answer here:
Why cannot directly assign this value to variable?
(1 answer)
Closed 1 year ago.
I'm writing a "dash system" in the Unity. And this sytem have a cooldown. And cooldown code is giving an error. My characterMovement script is here:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
//Normal Movement
public Vector3 vel;
public float speed;
public Rigidbody rb;
private bool isGrounded;
public int level; // I don't use this variable
//Dash
public float DashPower;
public Vector3 DashVel;
private float DashCooldown;
void Awake(){
speed = 3.25f;
DashPower = 8f;
DashCooldown = Time.time + 5.55f;
}
void OnCollisionStay(){
isGrounded = true;
}
void Update()
{
rb = GetComponent<Rigidbody>();
vel = new Vector3(Input.GetAxis("Horizontal"),0f,Input.GetAxis("Vertical"));
transform.position += vel * speed * Time.deltaTime;
DashVel = new Vector3(Input.GetAxisRaw("Horizontal"),0f,Input.GetAxisRaw("Vertical"));
if(Input.GetKeyDown(KeyCode.Space) && isGrounded){
rb.AddForce(new Vector3(0f,1.25f,0f) * 5, ForceMode.Impulse);
isGrounded = false;
}
if(Time.time >= DashCooldown){
if(Input.GetKeyDown(KeyCode.Q)){
transform.position += DashVel * DashPower * Time.deltaTime;
}
}
}
}
And my code giving this error: O
PlayerMovement.cs:12 = public Rigidbody rb;
I checked your script, and does not throw the compilation error you mention.
Make sure that at the time you save your scripts and compile, you dont have any initialization logic in the variable declaration.
At the class construction time, the compiler expects constant values in the variables, that is why you cannot for example set the array length with a variable at the point of variable declaration.
I believe this has to do with the fact that a field initializer cannot reference the non-static field, method, or property 'name' in c#. You can check the documentation for better understanding.
For example this lines also throws the compilation error you mention, because you trying to set the variable with logic at declare time.
private Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Check this, where I got the line that throws the error example and checked it actually does throw the error.
On the other hand, nothing to do with the problem but you can do the rb = GetComponent<Rigidbody>(); in the Start() or the Awake() instead of the Update(), as you just need to keep the reference to have it available within the class that is better that search for each every frame in the Update().
I'm a Unity beginner.
I have a problem with my script: in the picture above, Player item does not exist in Move script.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public float speed;
public Transform player;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
transform.Translate(x * speed * Time.deltaTime, y * speed * Time.deltaTime, 0);
Vector2 v2 = Camera.main.ScreenToWorldPoint(Input.mousePosition) - player.position;
player.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(v2.y, v2.x) * Mathf.Red2Deg);
}
}
I am not sure if I understand you right, but as this script is the script that belongs to the Player Gameobject, you don't need to specify "public Transform player".
The Gameobject class inherits from the Transform class, so it should work if you try:
Vector2 v2 = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(v2.y, v2.x) * Mathf.Red2Deg);
Maybe to make it more clear:
You don't need to have Player as an "item" that you pull into the according field in the inspector as it was the case if you relate to a gameobject which does not contain the "Move" script.
So, if you attach a script to a gameobject (in this case you attach the script to "Player"), then any methods you script, are directly affecting the gameobject the script belongs to.
E.g. try the following:
void Update() {
if(Input.GetKeyDown("space")) {
Destroy(gameObject);
}
}
You will see that the circle, which forms your player, will destroy itself when you hit the space bar. The parameter "gameObject" refers to the gameobject the script belongs to.
I hope that helps you to understand that you don't need to specify an extra GameObject that needs to be linked to the script, as long as the Gameobject you want to manipulate contains this script.
how are you doing?
I am working on a simple mechanic of knockback where if my character collides with the name "enemy", the players rigidbody which is paraphrsased as (rb), has force added 'back'.
Here is my code, Please refer to where I outline with asterisk.
public class Move : MonoBehaviour
{
public float speed;
private Rigidbody rb;
public int health;
private float knockback;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody>();
knockback = 2f;
}
void OnCollisionEnter(Collision col)
{
if (col.gameObject.name == "enemy")
{
health = health - 20; //**this works**
rb.AddRelativeForce(Vector3.forward * knockback); //**but this doesnt :c **
}
}
void death()
{
if (health <= 0)
{
print("i died");
}
}
void playerWalk()
{
var x = Input.GetAxis("Horizontal") * Time.deltaTime * 75f;
var z = Input.GetAxis("Vertical") * Time.deltaTime * 5f;
transform.Rotate(0, x, 0);
transform.Translate(0, 0, z);
}
void Update()
{
death();
playerWalk();
}
}
The problem is as you may have guessed, My triggers do not work.
My health = health - 20; line works but my rb.addforce doesn't.
What could be the problem here? Thank you :)
edit 2#
Just want to edit this and say That I have figured out the problem. The problem was that my float value just was not high enough xD
As you wrote the snippet, ´rb´ is not a field, but a local variable inside the ´Start´ method. If you are getting an exception in the menctioned line, maybe it is because of this. If you want ´rb´ to be a field, accesible all arround the class methods, you'll need to declare it in the class body, like this:
public int health;
private float knockback;
private RigidBody rb;
// (...) the rest of your code
If this is not the case, just tell me and give us more info on your problem.
Try removing the deltaTime:
rb.AddRelativeForce(Vector3.forward * knockback);
The default ForceMode for AddRelativeForce is AddForce and does not require time scaling.
I am not expert but this is my answer....
You attached rigidbody to the transform....so changing rigidbody position equal to transform position...
You calling two methods in update...so they going to be continuously called....so you move transform forward direction with uparrow key.. But you add force only at collision enter...collision enter is called only one time but playerwalk method is called continuously...that's why add force is not recognised.... Check this link
http://unityweltech.blogspot.com/2018/09/rbforce-is-not-responding.html?m=1