#💻┃code-beginner
1 messages · Page 354 of 1
yes i know
no im trying to get it from the MeteorFireScript so it can take the "bullet" rb2d since its a different gameobject
hatebin
i havent used that
ohh im mixing up people
ohhh
sorry sorry.. lookin at two different scripts 😄
u want the rigidbody from the same object as the MeteorExplosion..
well, right now ur trying to get the rigidbody from the object.. the script is attached to.. not the explosionScript object..
GetComponent is just referencing This gameobject...
for it to reference another object u need to prefix it:
thatOtherObject.GetComponent<Rigidbody2d>();
i know but i want it from the same item as the script is in
so. if the rigidbody is on the MeteorExplosionScript object..
you'd just access it via the variable u assigned just above it..
explosionScript = GetComponent....
explosionScript.GetComponent<Rigidbody2D>();```
what can i do to send my code?
ohh
use one of those links like the other guy did..
send the MeteorFireMovementScript.. b/c thats the script the error belongs to 👍
maybe im just trying something with the rotation that doesnt work or doesnt make sense
idk could be
my brain operates in weird ways
soo, errors 101:
- the number at the end of the error indicates the line number the error is on
- if there are (2) numbers, the first number is the character number, and the 2nd is the line number
transform.rotation = Quaternion.Euler(0, 0, explosionScript.amountOfBullets * (explosionScript.fireAmount / 360));
``` Something on this line isn't assigned..
so can i do this?
https://hastebin.com/share/xocecewoxe.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
soo unity spits out an error when it reaches it
explosionScript most likely.. isn't being assigned correctly..
let me check
in what way? what part are u asking about?
they spawn as different gameobjects instead of children
thats the problem
👍 good eye
how do i change the instantiate to make them childrens?
the problem is that when i shoot, the bullet go to the bullet hole, but if i shoot to an obstacle or the floor and then i shoot to the sky, the bullet go to the last bullet hole
this is the other script
https://hastebin.com/share/deruruhali.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you can
use gamething.parent = parentYouWantToSet;
orr another way is to use the Instantiate overload that lets u set the parent as one of the parameters
oh didnt know you could do this
this one here for example..
u could pass in the parent at teh same time u instantiate..
either or will work
so i just need to add transform after the transform.rotation?
you should use an else statement.. that way if the raycast doesn't hit anything (which is whats happening when u shoot into the sky)
it just doesn't spawn a bullet hole
b/c if theres no hit.. it can't replace the old position u assigned
how can i make that?
Hey there,
So basically I have Defence tower game like pvz, where you drag and drop characters in specific check points, I want to change the color of the object once it is in the same checkpoint where another object that contains the script “TissueObject” exists.
Here is my code the issue is I don’t know how think of the logic because i am dealing with three colliders, the collider of the tissue game object itself and the collider of any other tissue game object and the checkpoint
if (Physics.Raycast(ray, out RaycastHit hit, distance))
{
Debug.Log("Hit something with the raycast.");
// Spawn the Bullet Hole
}
else
{
Debug.Log("Didn't hit anything with the raycast.");
// Don't Spawn the Bullet Hole
}
``` ❔❓❔
if you aren't comfortable with using if else statements.. u probably wanna slow down a bit and try to solidify ur beginner coding concepts
I also want the way to be efficient not like Foreach, because it traverses all the elements which affects performance in case I have numerous elements.
if u want it to be a child of the gameobject spawning it.. yea, its pretty much that simple..
referenceToSpawnedThing = Instantiate();
referenceToSpawnedThing.parent = gameObject;
// or
referenceToSpawnedThing.parent = this.gameObject; // i like to use *this* to make things super readible
yay
thx, i´ll try it
a simple solution would be to use tags to tag each collider
I think that just be looping on all elements, I want a cleaner way
if(other.CompareTag("Thing1"))
{
// do thing1 action
}```
switch statement and a forloop
could check for components if each collider has a different script
TryGets aren't expensive
and where i need to put that script?
idk bro
You're already calling GetComponent in Update so you ought not to worry at all about minor details like foreach
Any reason why JsonUtility.ToJson(levelCompletionInfo) always writes empty string?
ur already raycasting somewhere for positioning ur bulletholes..
wherever that raycast is.. ur apprently setting the position of that bullet hole..
sooo... whenever you raycast fails don't add a bullethole..
i have this error
How should I do that
The problem I am facing is that the collider of the tissue I am dragging has the possibility to collide with one of them basically there are at least 2colliders 1 for the check point and the other is for the tissue if I place the tissue there and then drag another tissue towards it I don’t know which one it would collide with
When I tried compare tag it didn’t even work
I don't draw bullet holes, but my test raycast does something similar..
If the Raycast hits then the if statement runs.. and I set the hit variable..
if the Raycast misses then the else statement runs.. and I set the hit variable to null
may have to add an additional check.. if ur currently dragging (the object is moving) don't check
if ur hovering or have stopped dragging then check
not sure of ur set-up or ur game's goals.
I already did that
Generally sharing the error message would be appropriate
As well as reading it yourself
ok
You're trying to use variables that don't exist
i change the hit to my variable hitInfo
You can only use variables that have been defined
okay i still cant figure out how to get my character to go behind the decoration when its y is higher, i followed the tutorial but its just not working
u just copied and pasted..
the reason mine works.. is because i have all those variables set up already
Maybe have the backfield serialized? (backfield is private with public access to getter/visible-in-the-inspector)
Json: https://docs.unity3d.com/ScriptReference/JsonUtility.ToJson.html
Internally, this method uses the Unity serializer; therefore the object you pass in must be supported by the serializer: it must be a MonoBehaviour, ScriptableObject, or plain class/struct with the Serializable attribute applied. The types of fields that you want to be included must be supported by the serializer; unsupported fields will be ignored, as will private fields, static fields, and fields with the NonSerialized attribute applied.
Suggestion:[field: SerializeField]
(Have not tested)
how can i change that variables?
ray is a Ray variable..
hit is a RaycastHit variable..
distance is a Float variable..
you have to create them..
ok
yup, that's it 👍
I only read the part about 'class with serializable attribute' and not the next line lmao
i made it transparency sort by custom axis like the tutorial says but my main character is always on top anyway, they are on the same layer level
float distance = 50f;
Ray ray;
RaycastHit hit;
ray = new Ray(cam.transform.position, cam.transform.forward);
if (Physics.Raycast(ray, out hit, distance))
{
Debug.Log("Hit something with the raycast.");
}
else
{
Debug.Log("Didn't hit anything with the raycast.");
}```
heres the full block w/ the context.. (but u still can't just copy and paste)
you need to know how this stuff is arranged in the code, for it to be any kind of benefit to you
Hi again, back again with a humbling experience with git and git lfs and an overzealous gitattributes file, I think.. and this source control setup is a little.. complex.. and I'm slowly losing any confidence with my attempts at using version control
So I am using git and have the unity gitignore which is good, according to all. Git LFS has option 1 of using the popular gitattributes https://gist.github.com/nemotoo/b8a1c3a0f1225bb9231979f389fd4f3f or option 2, a version of it from someone who sounds like they know better than most on some quirks with it https://github.com/FrankNine/RepoConfig/blob/master/.gitattributes so I chose option 2 out of desperation for something I didnt have to mess with just in case
I got it set up, pushed changes, life was good... very long story short is that I reverted some changes, files stuck around still, I created my Unity project with spaces in the name, git doesnt allow that. Deleted the project, pulled latest from git, so I now have a differnt folder name which may not matter? Anyways loaded it up in unity and it worked but some addons I was using had missing required files which had me reimporting the entre assets and just caused a huge mess. I ended up just scrapping it all and starting over.
What am I doing wrong here?
Commit -> Push
Pull <- Commit -> Push
commiting and pushing are the only things u really need to know how to do
if ur not working in a team
Thanks, I'll just scrap the whole LFS thing and just try to push stuff that isnt media that the default gitignore doesnt catch and save it elsewhere
I had a feeling I was overthinking it and I guess I was. This stuff is quite complicated. I'm used to another source control so git is a little odd in how it treats all of the deltas for a file which is how LFS was made to sort of deal with that, but, messy
Consider Fork
I've been using it for little over a year now..
I don't know a whole lot about Git but its been easy enough for me to just keep backups on Git
I'll consider it. Unfortunate that it costs money for something I would only use for this type of stuff
Ya, I try to avoid pushing too many assets..
I had one project where I pushed an Audio Library.. and it got soo bad it finally corrupted and I had to go back and get a backup from my Local Harddrive
i kept the library locally.. and only pushed the audio I used from then on.. And i still work that way.
The program I just clipped is Free
basically an alternative of GitDesktop
It's showing $60 for me with an evaluation period?
but while you learn VC I'd suggest keeping Local Backups on ur HD or GDrive or something, until u feel comfortable..
i know thats kinda missing the point of VC.. but its some piece of mind when your working on a project that has weeks, if not months, invested in it
ohhh crap mb man.. i guess it's gone Paid since I downloaded it
oh wait.. the evaluation is indefinitely free..
they just ask for donation from time to time i guess
Oh ok, thats not bad then. I'll give it a shot. But yeah anwyays back to my issue though I'll just use the unity gitignore, throw stuff on a repo and make some local backups every now and then and call it a day
Thanks for the help
ya, sadly i can't help with LFS stuff.. I had to have a colleague of mine walk me through it last time I used it
and even then I really didn't even use it for much.. so I haven't used it since then.. and that was a year or more ago..
so far all of my projects work fine with regular Git..
google drive gives you 15 GB.. so thats a good place to store your audio / graphic libraries that would eat up alot of space
i use that, i think i know how it works, but when i shoot to the sky, the debug text "Didn't hit anything with the raycast." doesn´t appears
I even tried putting it as you said still does not work!
https://paste.ofcode.org/Ebp5AgVeQDJpgsk9U3urzF
@rocky canyon
Hi, I'm doing some procedural animation stuff and I'd like to be able to test the parameter changes on animations without running the scene. Are there any methods like OnDrawGizmos that get called outside of scene execution where it would be appropriate to do this? (accidentally asked on the advanced channel, deleted that one and reposted here)
Why does it complain about getting null when .Add(test) but for the if statement test is not null. line 19 is just calling the function. Any clue? thanks.
maybe calling .Add on a null object. enemyGroups_Enemies could be null
You can use [ExecuteAlways] on the script class to get Update also working in edit mode.
ok awesome thanks. Is there a way of toggling this from the inspector?
yes, thanks
btw instead of an if else statement you can Debug.Log(test == null);
No, you'd have to check it yourself.
[SerializeField]
private bool updateInEditMode;
private void Update()
{
if (!Application.isPlaying && !updateInEditMode) return;
}
Universal methods to make your life easier!
Takes in a float value and an image or text and sets the alpha to the specified value
public static void SetImageAlpha(Image image, float alpha)
{
if (image != null && image.color.a != alpha)
{
float R = image.color.r;
float G = image.color.g;
float B = image.color.b;
float a = alpha;
image.color = new Color(R, G, B, a);
}
}
public static void SetTextAlpha(TextMeshProUGUI text, float alpha)
{
if (text != null && text.color.a != alpha)
{
float R = text.color.r;
float G = text.color.g;
float B = text.color.b;
float a = alpha;
text.color = new Color(R, G, B, a);
}
}
Best used in a static class
legend, thank you!
is there an execution order of awake() for different game object scripts? or can I create an execution order?
There is not
The only way you can define it would be to have your own method that you call from a single object in the specific order you want
The need to do so is a bit of a concern though.
What problem are you wanting this solution for?
i have 2 scripts, 1 assigns a value to a variable, name, in Awake, the other script in Awake gets the name variable. In this case, i can try to move the get part to start then, thanks for the info
Yes, always do SELF-referencing only in awake. Do external referencing in start. Even that isn't enough sometimes, but it always is fine for objects that exist before runtime starts. It is only with instantiating that it isn't guaranteed
But yesterday when possible best to avoid
private void OnTriggerStay2D(Collider2D other)
{
if (other.TryGetComponent(out Green_Script green))
{
Debug.Log("Green is nearby!!");
}
if (other.TryGetComponent(out Red_Script red))
{
Debug.Log("Red is nearby!!");
}
if (other.TryGetComponent(out Blue_Script blue))
{
Debug.Log("Blue is nearby!!");
}
}```
I was mentioning using `TryGetComponent` which is alot better than setting a variable using `GetComponent` and then checking for `null` afterwards..
not sure what about your script isn't working.. But my bet is the setup.. Might try revising it a bit to make it work better for the dragging mechanic..
I just put my code on my mouse cursor b/c I don't have a dragging system to test yet..
setup is just Empty Script sitting on the Collider
Hi everyone, I'm trying to get an object to follow my mouse in a room (like first video). I use raycast to determine the object I want to move and move the object following to the position of the mouse on the screen. But when i hit play and drag the object, it doesn't move like in the first video, the object will move like in the second video. Anyone know how to make the object move like the first video? Thanks a lot!
My code:
using UnityEngine;
public class Trash : MonoBehaviour
{
[SerializeField] private Camera mainCamera;
private GameObject _selectedObject;
private Vector3 _originPos;
private bool _dragging;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (!_selectedObject)
{
var hit = Cast();
if (hit.collider)
{
if (!hit.collider.CompareTag("trash")) return;
_selectedObject = hit.collider.gameObject;
_originPos = _selectedObject.transform.position;
}
}
}
if (_selectedObject)
{
var pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y,
mainCamera.WorldToScreenPoint(transform.position).z);
var newPos = mainCamera.ScreenToWorldPoint(pos);
_selectedObject.transform.position = newPos;
}
if (Input.GetMouseButtonUp(0))
{
if (_selectedObject)
{
_selectedObject.transform.position = _originPos;
_selectedObject = null;
}
}
}
private RaycastHit Cast()
{
var ray = mainCamera.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(ray, out RaycastHit hit);
return hit;
}
}
I kinda see what ur going for now.. but the tissues detecting the collider?
i was thinking it was backwards.. your object was detecting the tissue
you need some way of telling the object its up against a wall and shouldnt move any farther
all u need is some bounds
can manually set them.. or could use a box collider or something...
then clamp the position so it doesn't move any farther
BoxCollider room;```
```cs
Vector3 minBounds = room.bounds.min;
Vector3 maxBounds = room.bounds.max;```
```cs
position.x = Mathf.Clamp(position.x, minBounds.x, maxBounds.x);
position.y = Mathf.Clamp(position.y, minBounds.y, maxBounds.y);
position.z = Mathf.Clamp(position.z, minBounds.z, maxBounds.z);
``` something like this makes sense to me
unless the room is an odd shape.. and then i'd have to think a bit more about it
I see, i will try it
Thanks a lot!!
good luck 🍀
Whenever I am on the ground my velocity continues to rise up until i jump, which is the only time it resets
this is my code:
cs
// using System.Collections;
using System.Collections.Generic;
using Unity.Jobs.LowLevel.Unsafe;
using UnityEngine;
using UnityEngine.Rendering;
public class EX_CharacterMovement : MonoBehaviour
{
public float walkSpeed = 0f;
public float runSpeedMultiplier = 1.5f;
public float jumpForce = 0f;
public float groundCheckDistance = 1.5f;
public float lookSensitivityX = 0f;
public float lookSensitivityY = 0f;
public float minYLookAgnle = -90f;
public float maxYLookAgnle = 90f;
public Transform playerCamera;
public float gravity = -9.81f;
private Vector3 velocity;
private float verticalRotation = 0f;
public CharacterController characterController;
private void Awake()
{
characterController = GetComponent<CharacterController>();
Cursor.lockState = CursorLockMode.Locked;
}
private void Update()
{
float horizontalMovement = Input.GetAxisRaw("Horizontal");
float verticalMovement = Input.GetAxisRaw("Vertical");
Vector3 moveDirection = transform.forward * verticalMovement + transform.right * horizontalMovement;
moveDirection.Normalize();
float speed = walkSpeed;
if (Input.GetAxisRaw("Sprint") > 0)
{
speed *= runSpeedMultiplier;
}
characterController.Move(moveDirection * speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && IsGrounded())
{
velocity.y = jumpForce;
}
else
{
velocity.y += gravity * Time.deltaTime;
}
characterController.Move(velocity * Time.deltaTime);
if (playerCamera != null)
{
float mouseX = Input.GetAxisRaw("Mouse X") * lookSensitivityX;
float mouseY = Input.GetAxisRaw("Mouse Y") * lookSensitivityY;
verticalRotation -= mouseY;
verticalRotation = Mathf.Clamp(verticalRotation, minYLookAgnle, maxYLookAgnle);
playerCamera.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);
transform.Rotate(Vector3.up * mouseX);
}
}
bool IsGrounded ()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit, groundCheckDistance))
{
return true;
}
return false;
}
}
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I feel dumb whenever I start trying to understand what I'm doing, does anyone have good tips for me to learn?
learn the basics using courses like the ones pinned in this channel, then just keep making stuff and learning new concepts as you need them. understanding comes with practice and experience
you should keep ur downwards velocity a constant while grounded.. instead of adding on to it over and over..
thats fine to do while ur airbourne.. but when grounded.. it shouldn't be accumulating
gravitySim is just a vector that gets added to the input vector i pass into my Move() function
So add on that void to the end of my code?
they're Methods or Functions.. void is the return type (so those functions don't return a variable)
and right here is where u keep adding the gravity... soo in there you could adjust how ur gravity logic is working..
no.. u can't just add it on.. u have to adapt it to the script u already have..
for 1 you don't call a function called ApplyGravity(); anywhere.. and even if u did the gravitySim variable isn't declared or used for ur characters move() function
oh okay thank you
are you following a tutorial? they should cover how to fix that..
i am however they do not cover it
b/c its a big issue.. esp if u walk off the top of a ledge or something
b/c you'll get hurled into the ground if ur velocity keeps growing 😄
yeah dont want that lmao
private void Move()
{
ApplyGravity();
CalculateSpeed();
finalVector =
(groundVector * finalSpeed) +
(airVector * playerSettings.airSpeed) +
(Vector3.up * gravitySim);
if (jump.magnitude > playerSettings.jumpMagn)
{
finalVector += jump;
}
characterController.Move(finalVector * Time.deltaTime);
jump = Vector3.Lerp(jump, Vector3.zero, playerSettings.jumpSmoothing * Time.deltaTime);
}```
for context here is my Movement function
im still a little new to c#, what does the final vector do?
the finalVector i pass into my CCs Move() function is created by adding abunch of different vectors.. and then my gravitySim
it does the same thing as ur moveDirection
and then gravity sim is its own declared float/var?
its made up of inputs just like urs
this funciton is called in Update.. runs every frame
it gets all my vectors.. like urs.. and then adds in the gravity variable.
the AddGravity(); is also called every frame..
so its constantly either setting the gravity to 1 steady value (when grounded)
or.. adding onto it (if not)
so i make the addgravity void and then declare it in the update void?
ah mb
void is its return type..
ohh okay
like ur IsGrounded() method's return type is bool
it's not work at all :((
it could be a function.. as well public void IsGrounded().
yeah to see if is isgrounded, true or opposite
but hta wouldn't give u back ur true or false..
everytime this if/else runs.. that method returns it a bool.
so its basically like having a true/false right there in the if condition
is that a bad thing?
nah not at all..
https://www.spawncampgames.com/paste/?serve=code_777
i thought this was gonna be a lot more simple lol
heres a look at my CC... for context
ok
have you looked over ur script so u know what it does?
what does serializefield do?
and how it works? or is just copy-pasta
you know how theres public and private fields?
public variables can be accessed from outside scripts..
which alot of the times u dont want..
so u make a private variable instead.. so it can only be accessed within the script its in
oh okay gotcha
[SerializedField] can take a private variable.. and show it in the inspector..
so u can keep a variable private.. but still be able to assign it with the slot.. or see if its there
gotcha
i have alot more visible than i should. for debugging..
like i can see my gravitysim
as its working
oh and then i see how you did headers for organization i likethat
ya, it gets complicated and i have to keep up with whats what
true
but line 154 is where my apply gravity function is..
i see.. and then where would i define it in my script
and then i just do that modification before i pass in the vector to my cc
!code well if u'd post ur code correctly, i'd be able to pinpoint it for you a little better
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
how do i do that sorry
read the Bot message ^
use any of those links is the best thing
just paste ur code in, save it, and it'll give u a url to paste back
if u can see it, we can see it
oh ok
i just noticed you have 2 Move() functions
I do?
you do.. you have 1 where u pass in ur movement vectors
and then under the jump check u have another
interesting.
i'd make it just 1cs Vector3 combinedMovement = moveDirection * speed + velocity; characterController.Move(combinedMovement * Time.deltaTime);
if (IsGrounded())
{
if (velocity.y < 0)
{
velocity.y = -2f; // Small negative value to keep grounded
}
if (Input.GetButtonDown("Jump"))
{
velocity.y = jumpForce;
}
}
else
{
velocity.y += gravity * Time.deltaTime;
}``` and then i'd do something like this.. where *if* ur grounded u either set ur gravity to constant `=` or jump and set it to ur jumpforce.. oor your *not* grounded.. and then u can add ur increasing gravity `+=`
well now whenever I hit the ground It lilke slows the fall down right before i hit it
like im falling noramlly and it works, but right before I hit the ground my fall slows down
whatever you are using to ground check is checking too far
im using a raycast
then your raycast is too long
I added a background in my canvas. But I have an issue where the 2D Game Objects are behind the canvas. How do I bring them in front of the background? Or do I have to make the background in world space?
First of all I think your message doesn't belong here, maybe you should ask in #💻┃unity-talk , this is a code channel.
But I have something similar as you can see on the image so I'm going to answer how I did it if you are looking for something similar. What I do is create a Render Texture and associate with the Target Texture of the Camera component. After that on your UI you can create a RawObject that can also be associated with the RenderTexture. Just imagine it like a stream, where the camera is recording on a TargetTexture and you can see that stream on a RawImage like a screen. After that is working you can do some improves like adding the aspect Ratio Fiter on your RawImage to ensure the camera image won't be stretched or compressed and you can preserve the original aspect ratio.
Maybe there is a better way to do that, but I'm kind of new and this is the only way I found.
For me what worked was creating different sorting layers. So my background image is on the first layer, meaning anything on layer 2 and more will be displayed in priority, and thus end up in front of the background
i forgor the name of the thing where you want to have states instead of strings
do you perhaps mean an enum?
{
if (EnemyWeapon.hitTime < PlayerWeapon.hitTime)
{
playerWeaponHitFirst = true;
instance.playerAttackedFirst = true;
instance.battleActive = true;
}
else
{
enemyWeaponHitFirst = true;
instance.enemyAttackedFirst = true;
instance.battleActive = true;
}
}``` This class is on my game manager but when i enter a battle i want to change playerWeaponHitFirst to false how can i change a static value thats in a function
show the declaration of playerWeaponHitFirst
btw this statement 'a static value thats in a function' makes no sense
You can always change a static value. No instance needed. I assume you worded your question wrong.
Hi can someone help me why it isn't working?
How do you make it so that text inputfields don't automatically activate when they're selected with a controller movement input?
Did you attach it to the object?
Does the object have a collider?
If this is for UI you should be using IPointerDownHandler and IPointerEnterHandler
BTW Button has a built-in sprite transition mode thing
You don't need to write this code
Maybe I'm blind but I haven't seen field for sprite
Change transition mode to sprite swap
Damn. Thanks a lot
how do i make a normal tile?
This is a coding channel
apologies i dont know where im meant to go for this type of question
using BehaviorDesigner.Runtime.Tasks;
using Character.Survivors;
using NPC.Tasks.Survivor;
using Quests.Main;
using UnityEngine;
using UnityEngine.AI;
public class Flee : Action
{
[SerializeField] private Transform killer;
public DoQuest doQuest;
public SharedTransform MainQuestInRange;
private NavMeshAgent survivor;
public float safeDistance = Random.Range(31f, 45f);
public override void OnStart()
{
survivor = GetComponent<NavMeshAgent>();
killer = GameObject.FindGameObjectWithTag("Killer").transform;
if (doQuest._mainQuest != null)
doQuest._mainQuest.InterruptQuestBot();
}
public override TaskStatus OnUpdate()
{
if (doQuest._mainQuest != null)
Debug.Log("Flee" + doQuest._mainQuest.mainQuestStatus.Value + " " + doQuest._mainQuest.gameObject.name);
if (killer == null)
{
return TaskStatus.Failure;
}
float distanceToKiller = Vector3.Distance(transform.position, killer.position);
Vector3 dirToKiller = transform.position - killer.position;
Vector3 newPos = transform.position + dirToKiller.normalized * safeDistance;
if (distanceToKiller < safeDistance)
{
NavMeshHit hit;
if (NavMesh.SamplePosition(newPos, out hit, safeDistance, NavMesh.AllAreas))
{
survivor.SetDestination(hit.position);
}
}
else
{
return TaskStatus.Success;
}
return TaskStatus.Running;
}
}
Hey y'all i have a problem with this code, i want my AI agent to run from the killer, so I made it run to the opposite direction, the problem is, whenever my agent faces the wall or a static object from the environment it stops for a few seconds, what should i do to prevent that from happening?
hi chat, been following alongside this brackeys video and i'm nearly done with creating my boss, however i've ran into an issue where when i try to set my boss to be able to deal damage to my player but when i've tried to code that in alongside him, it gives me this issue posted below. and you can also see i've added player health but it doesn't want to access it (unless i've missed him adding a reference to my player script)
https://youtu.be/AD4JIXQDw0s?si=sVuzXYmoYgyTdWx6 at 15:38
What's more awesome than an epic boss battle? Let's make one using state machines!
Get 42% OFF Nordlocker: https://nordlocker.net/brackeys
Use code: "BRACKEYS"
● This video is inspired by: https://youtu.be/cXefXSD2SM
● Project Files: https://github.com/Brackeys/Boss-Battle
More videos about 2D:
● 2D Animation in Unity: https://youtu.be/hkays...
also didn't mean to text over this other guy's message, have a look above if you can help him 🙏
do you have a script called currentHealth?
i might be an idiot
yea thanks it worked 😭
Again, #854851968446365696 as you are repeatedly doing Don'ts
Just ask your question
That's not your actual question is it
Great well you're not getting any help then
!mute 1119185460930039848 15m when you're back you better have changed your pronouns to not be homophobic, and actually ask the real question instead of asking whether people can help with a question you refuse to just ask.
ohmohctp was muted.
ok so im running into an issue with colliders
basically im using an a* enemy movement system which means that the system works with two colliders; one 2d box collider thats used as an actual hitbox for player attacks and another 2d circle collider which is used only for navigation and making sure enemies don't get stuck on obstacles while pathfinding
this is what an average enemy with this a* pathing algorithm looks like
problem im running into is with how my system works for one of the player's abilities
basically the player has a "bite attack" that for every collider spawns a pickup, and it spawns 2 per enemy right now, when i only want it spawning one
actually might have figured something out
Okay i tried my best trying to solve this on my own but were not able to. im currently making my first project which is a 2d hidden objects game. ive been working on mouse nagivation on screen and were able to make both dragging and zooming with mouse wheel to work. but trying to add a camera boundry has prop been the hardest thing in this project.
The game doesnt have a player character but has a custom cursor which ive tried using as a tracking point for the boundry. but i cant seem to fix the issue that when i try to run the game and drag it changes Z from -10 to 0 so i lose view of the game scene. ps. i really had no experince with coding before this project, so this is all very new. i tried incorporating the working CameraMove code that allowed for dragging of the screen with a new code that were supposed to track a player character and lock its camera view, but tried altering it for my need.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
[SerializeField]
GameObject player;
[SerializeField]
float timeOffset;
[SerializeField]
Vector2 posOffset;
[SerializeField]
float leftLimit;
[SerializeField]
float rightLimit;
[SerializeField]
float bottomLimit;
[SerializeField]
float topLimit;
private Vector3 Origin;
private Vector3 Difference;
private Vector3 ResetCamera;
private Vector3 velocity;
private bool drag = false;
private void Start()
{
ResetCamera = Camera.main.transform.position;
}
private void LateUpdate()
{
void OnDrawGizmos()
{
//draw a box around our camera boundary
Gizmos.color = Color.red;
//top boundry line
Gizmos.DrawLine(new Vector2(leftLimit, topLimit), new Vector2(rightLimit, topLimit));
//right boundry line
Gizmos.DrawLine(new Vector2(rightLimit, topLimit), new Vector2(rightLimit, bottomLimit));
//bottom boundry line
Gizmos.DrawLine(new Vector2(rightLimit, bottomLimit), new Vector2(leftLimit, bottomLimit));
//left boundry line
Gizmos.DrawLine(new Vector2(leftLimit, bottomLimit), new Vector2(leftLimit, topLimit));
}
Vector3 pos = transform.position;
pos.z = -10;
transform.position = pos;
if (Input.GetMouseButton(0))
{
Difference = (Camera.main.ScreenToWorldPoint(Input.mousePosition)) - Camera.main.transform.position;
if(drag == false)
{
drag = true;
Origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
else
{
drag = false;
}
if (drag)
{
Camera.main.transform.position = Origin - Difference * 0.5f;
Camera.main.transform.position = Origin - Difference;
Camera.main.transform.position = new Vector3();
Mathf.Clamp(transform.position.y, leftLimit, rightLimit);
Mathf.Clamp(transform.position.y, leftLimit, rightLimit);
}
if (Input.GetMouseButton(1))
Camera.main.transform.position = ResetCamera;
}
}
the rubber duck effect works
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok so this is my current code which uses colliders instead of gameobjects like i want
{
Collider2D[] hitColliders = Physics2D.OverlapCircleAll(transform.position, 5);
foreach (Collider2D collider in hitColliders)
{
if (collider.CompareTag("enemydead"))
{
// collider.transform
PickupGeneration(collider.transform.position);
GameObject hitObject = collider.gameObject;
legitkills++;
print(legitkills + "killscount");
Destroy(collider.gameObject);
//animator.SetTrigger("Eating");
}
}
}```
i assume thats meant for me, i will try to reformat it, thanks
i can use a distanceto function to look for enemies with the "enemydead" tag no problem
but is there a foreach function i can apply to all gameobjects in range?
an overlapcircle would not work since thats looking for colliders, and every enemy with a* pathing has 2
if you have the enemies in a list, you can loop to check their distance . . .
i could stick that in the levelmanager
because the issue is some enemies have a* pathing, others dont
also, you can filter the what colliders are searched based on layers. this will only check for colliders on specific layers . . .
can you manually set layers per collider
it's per GameObject. this will remove the enemy tag check . . .
if you place the collider GameObject on an enemy layer, then every collider in that array will be an enemy . . .
or what ever layer name you need . . .
what i could do is parent the a* collider, and give it a tag to ignore the player completely
then in the foreach function add something to make it ignore all colliders with that tag
yes, you can use the layer matrix to allow layers to ignore layers . . .
you can use a component, interface, or enum for that as well, instead of relying on a tag . . .
Unity tags suck because they aren't bitwise
i gathered
ugh this is kind of a headache
ok what if i gave the colliders which need to be ignored a material, and if a collider has that material it gets skipped
basically a bootleg tag for that collider
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
that seems like extra work. just use any of the options noted above . . .
ok so what type of component would i use
https://gdl.space/uzijuyosis.cpp okay i seem to confuse how to rotate the children at the moment of instantiating it, or maybe im confusing how transform.up works, but im guessing its rotation because when i check it has rotation 0 https://gdl.space/akogaxejoz.cs
no, you would check for a component those enemies have (in common). it's just like a tag, but not error-prone . . .
My NPC will freeze when it starts it's suspicion behavior before moving back to patrolling.
public class AIController : MonoBehaviour
{
[SerializeField] float suspicionTime = 3f;
float timeSinceLastSawPlayer = Mathf.Infinity;
private void Update()
{
if (health.IsDead()) { return; }
if (InAttackRangeOfPlayer() && fighter.CanAttack(player))
{
AttackBehavior();
}
else if (timeSinceLastSawPlayer < suspicionTime)
{
SuspicionBehavior();
}
else
{
PatrolBehavior();
}
UpdateTimers();
}
private void PatrolBehavior()
{
Vector3 nextPosition = guardPosition;
if (timeSinceArriveAtWaypoint > waypointDwellTime)
{
mover.StartMoveAction(nextPosition, patrolSpeedFraction);
}
else
{
mover.Cancel();
}
}
private void SuspicionBehavior()
{
mover.Cancel();
}
}
public class Mover : MonoBehaviour, IAction
{
private Direction lastMovementDirection;
private Vector2 lastDirection;
public bool isMovingAnimationSet = false;
[HideInInspector]
public bool isIdling = true;
private enum Direction
{
Left,Right,Up,Down,None
}
private void Update()
{
bool isDead = health.IsDead();
rb.isKinematic = isDead;
capsuleCollider.enabled = !isDead;
Debug.Log(isIdling);
}
private void FixedUpdate()
{
if (rb != null)
{
rb.velocity = velocity;
}
}
public void StartMoveAction(Vector2 destination, float speedFraction)
{
if (!isMovingAnimationSet)
{
isIdling = false;
isMovingAnimationSet = true;
ChangeAnimation("Walk", GetLastDirection());
}
MoveTo(destination, speedFraction);
}
public void MoveTo(Vector2 destination, float speedFraction)
{
Vector2 currentPosition = transform.position;
Vector2 direction = (destination - currentPosition).normalized;
velocity = direction * maxSpeed * Mathf.Clamp01(speedFraction);
Direction currentMovementDirection = GetMovementDirection(direction);
if (currentMovementDirection != lastMovementDirection)
{
lastMovementDirection = currentMovementDirection;
lastDirection = direction;
Debug.Log("Moving To");
ChangeAnimation("Walk", direction);
}
}
public void Cancel()
{
velocity = Vector2.zero;
if (!isIdling)
{
isIdling = true;
isMovingAnimationSet = false;
ChangeAnimation("Idle", GetLastDirection());
}
}
public Vector2 GetLastDirection()
{
return lastDirection;
}
public bool IsMoving
{
get { return velocity != Vector2.zero; }
}
}
your suspicion behaviour calls mover.Cancel which sets the velocity to zero (therefore, it stops motion). then it check for idle, setting to true and changes its animation to idle. it makes sense to me why it freezes . . .
does someone know the way to rotate it?
Motion should stop during suspicion for a few seconds and the NPC should idle in place and then walk back to it's last patrol point. MoveTo() seems to continuously get called when SuspicionBehavior() moves to PatrolBehavior(), which is setting the walk animation repeatedly.
it says i cant convert vector3 to quaternion
You can't
a vector3 is a position not a rotation
A vector3 is a vector. It's not necesserarily a position
i imagined that, but how could i change the rotation? i searched in the docs and found Euler.angles but that doesnt work either
But it's not a quaternion for sure
Well, what did you try?
yeah mb
this shows no error but then it doesnt rotate it at all
i edited the code from my previous post a bit so now the drag and reset works again but the boundry box and gizmo lines still dont work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
[SerializeField]
GameObject player;
[SerializeField]
float timeOffset;
[SerializeField]
Vector2 posOffset;
[SerializeField]
float leftLimit;
[SerializeField]
float rightLimit;
[SerializeField]
float bottomLimit;
[SerializeField]
float topLimit;
private Vector3 Origin;
private Vector3 Difference;
private Vector3 ResetCamera;
private Vector3 velocity;
private bool drag = false;
private void Start()
{
ResetCamera = Camera.main.transform.position;
}
private void LateUpdate()
{
void OnDrawGizmos()
{
//draw a box around our camera boundary
Gizmos.color = Color.red;
//top boundry line
Gizmos.DrawLine(new Vector2(leftLimit, topLimit), new Vector2(rightLimit, topLimit));
//right boundry line
Gizmos.DrawLine(new Vector2(rightLimit, topLimit), new Vector2(rightLimit, bottomLimit));
//bottom boundry line
Gizmos.DrawLine(new Vector2(rightLimit, bottomLimit), new Vector2(leftLimit, bottomLimit));
//left boundry line
Gizmos.DrawLine(new Vector2(leftLimit, bottomLimit), new Vector2(leftLimit, topLimit));
}
Vector3 pos = transform.position;
pos.z = -10;
transform.position = pos;
if (Input.GetMouseButton(0))
{
Difference = (Camera.main.ScreenToWorldPoint(Input.mousePosition)) - Camera.main.transform.position;
if(drag == false)
{
drag = true;
Origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
else
{
drag = false;
}
if (drag)
{
Camera.main.transform.position = Origin - Difference * 0.5f;
Camera.main.transform.position = Origin - Difference;
// Camera.main.transform.position = new Vector3();
Mathf.Clamp(transform.position.y, leftLimit, rightLimit);
Mathf.Clamp(transform.position.y, leftLimit, rightLimit);
}
if (Input.GetMouseButton(1))
Camera.main.transform.position = ResetCamera;
}
}
Did you try debugging the resulting value?
Also, it would only rotate at the scene start(or the object's Start), since it's in Start
what should i debug? the rotation?
wouldnt it rotate at the start of the instantiate command?
The value that you try to assign to the rotation(the one you ty to create a quaternion from)
thats what it should do
let me give you context of the other script
each time the loop happens it should go up by 1 fraction of a whole 360º that depends on the amount of bullets
so if there are 3 bullets
that doesn’t change the transform as a function of i tho
oh wait i think i messed up and the 360 should go at the start
Your OnDrawGizmos is inside of your LateUpdate function, you need to take it out.
Your question is barely understandable and your code doesn't show much since it is relying on a few other scripts we don't know nothing about; but it seems your issue is that you are just adjusting the text to be the variable "score" instead of making it a string with the word first (for example "public string score = "Score: " + score;)
Debug it then
where should it be and why should it not be inside of late update? i assume late update is a update that accours after update but still gets checked continuously?
It should be on outside as its own function in your class, not embedded inside another.
and that shouldnt be happening so imma go try to debug more things
amountOfBullets is in local scope.
You're probably not debgging the right thing.
local scope?
OnDrawGizmo will run itself every frame, you don't need to put it inside of an update function.
im doing debug.log(transform.rotation);
actually nvm it isn’t
And what type is transform.rotation?
sry i misread
what do you mean by type?
either way, the explosion script should call a method to pass information into the other script
A Type. You know, every object has a type in object oriented language like C#.
amountOfBullets should be a private variable
then you will know exactly what you are trying to pass in to the other script
WOW! they show up now thanks! but doesnt seem to lock the camera inside the boundry, imma see if i can make it work
GameObject obj = Instantiate(…);
BulletScript bullet = obj.GetComponent<BulletScript>();
bullet.AssignRotation(amountOfBullets…)(
this is how I would do it
i thought it was a vector3 but from what ive heard it isnt
Did you look it up in the API docs?
does it make sense what I am going for?
with a separate method, you can trace more easily exactly what is getting assigned to debug it
and also make sure the timing is right
also i think i figured out the problem
there are x amount of bullets spawning each round, how does the engine know to change the rotation to the latest one instead of just changing the rotation of one of them over and over?
because obj is the object you just instantiated
it can't possibly be any other bullet
if Instantiate returned a random object from your scene, it would not be very useful (:
i read the start and by type i think you mean int bool float vector3 vector2 etc etc
you use an IEnumerator, that goes through its loop all on yield return null. Those all get instantiated. Then later, Start is called after they are all instantiated, so they all work on the same value of explosionScript.amountOfBullets
no, the Unity documentation for transform.rotation
so the method you are using will never work without passing the information into the bullet script the way I described
No. I'm talking about the type of what you were debugging.
it tells you exactly what the property's type is!
ohhh
its a quaternion
this is definitely the source of digitalmonkey’s bug
or rather, it is definitely something that will block it from working
And that's how quaternions look. They have 4 members and the last one is usually equal to 1.
But then again, everything else being 0 means that it's not rotated.
okay i understand i think
and as loup said it probably is because it instantiates all of them and then each one tries to get the rotation which is 0 since its a complete cycle and therefore every bullet has 0 rotation?
each one reads the value in the script after it finished the loop. so they all use the same number
i might be explaining it in a weird way but i think i understand what the problem is
You should start with debugging everything. If you have assumptions, debug to confirm them.
as to whether or not the Quaternion math gets you the rotations you want is a different matter that fen and dlich are getting at
they are focused on getting the correct rotation given the right input
yeah if im using quaternions it surely isnt working
since the math is kinda weird
i wanted to use euler angles
in general, you want to multiply quaternions
a quaternion represents a rotation operator
rotation operator?
a single quaternion represents taking something with “no rotation” (identity), and rotating it in some way
that is what a rotation operator does. it apllies rotation
okay
quaternion multiplication corresponds to composition of rotation operators (which do not commute!)
commute?
A * B = B * A
that is the commutative property
and it does not hold for quaternions!
oh
(quaternion for 90Deg x rotation) * (quaternion for 90 deg y rotation) = (quaternion for both)
okay so basically the order of the factors dont alter the product
no, they do
they are associative
because the operation is not commutative
if it was commutative, then the order wouldn't matter
phew
commutative means order does not matter.
quaternion multiplaction is not commutative
yeah i mean that its basically that law but instead of correct its wrong
90 deg x then 90 deg y is not the same as 90 deg y then 90 deg x
okay
in general, if you do quaternionA * quaternionB, it’s like you start with rotation of quaternionB, THEN you rotate by quaternionA
cant i just use euler angles?
again: order matters
isn't it the other way around
the reason we use quaternions is because euler angles are fucky
transform.rotation *= Quaternion.AngleAxis(45, Vector3.up)
this always rotates you around the +Y axis
shouldnt it be that you start at quaternionA and rotate quaternion b=
?*
i thought it’s like matrices, so it should be the way I said
because of gimbal lock?
that is one reason
Rotating by the product lhs * rhs is the same as applying the two rotations in sequence: lhs first and then rhs, relative to the reference frame resulting from lhs rotation.
that's one problem, yeah
all the math of how euler angles work make them not behave well when applying rotation operators using them alone
gimbal lock is one symptom of that
but i just want to instantiate an object with a certain z rotation
okay, so use Quaternion.AngleAxis to compute the desired rotation
isnt that something basic that should give no problem with euler angles
Quaternion.AngleAxis(45, Vector3.forward) gives you a 45-degree rotation around the +Z axis
Quaternion.Euler(my desired rotation) * transform.rotation => new rotation
because im getting my mind blown by weird math and i just want to do a 101 thing
still backwards!
is it tho lol
yes
I remember it as parent * child
unless you intend to apply that rotation before your original world rotation
I had to learn all of this whilst writing code that stored position and rotation offsets from a parent to a child
i did it wrong in every possible way lol
i only learned about commutators and shit for rotation operators when I did physical chemistry via quantum mechanics. I didn’t learn any of that shit in normal physics classes
which is theoretically when you should learn it
why do i want to rotate a thing in the z axis and im just hearing that you are telling me things that get explained in a quantum mechanics class 
yeah, it makes more sense with group theory
you don't need to understand anything about quaternion math to use rotations
just like you don't need to understand linear algebra to use transform.TransformPoint
Just use the methods provided by Quaternion.
only thing to know is euler is a poopy head and likes to give you the gimbals
what is even linear algebra lmao
because your transform is 4x4 matrix that applies to the whole object
I'll give you ten points if you can remember where Quaternion.Inverse goes to calculate the rotation offset of a child to its parent. I always have to double check my old code.
Quaternion.AngleAxis, Quaternion.LookRotation, Quaternion.FromToRotation, ...
i heard that a bunch of times
but in 2d it shouldnt matter right?
for (int index = 0; index < spline.Count; ++index)
{
BezierKnot knot = knots[index];
Transform parent = transforms[index];
positionOffsets.Add(parent.InverseTransformPoint(splineTransform.TransformPoint(knot.Position)));
Quaternion knotWorldRotation = splineTransform.rotation * knot.Rotation;
Quaternion toParentRotation = Quaternion.Inverse(parent.transform.rotation) * knotWorldRotation;
rotationOffsets.Add(toParentRotation);
}
i think this is probably right
it works, at least
2d is fine for euler
it does because your transform is still a 4x4 matrix
and your transform.rotation is still a quaternion
2D rotation is conceptually simple, yeah
2 axis of rotation = not likely to run into gimbals
assuming you only spin around the +Z axis
copied code, you cheated 😠
because unity implements it all as 3D
then why am i hearing something about quantum mechanics lol
my brain is getting filled with things it can only dream to comprehend at the moment
in 2D, rotation can be represented solely as one number: z axis angle.
but unity uses the same transform framework for everything. So your transform is a 4x4, and your rotation is a quaternion (instead of just 1 number for an angle)
is there a working workaround to calling coroutines in a scriptableobject?
coroutine manager
because the underlying mathematics are more complicated
do you know what homogeneous coordinates are?
no clue
yet you are making a 3D video game!
how?
also the 4x4 transform matrix includes scale, position, and rotation
you don't need to know the intricate meaning of a 4x4 transformation matrix
you just need to know how to use the tools Unity gives you
yes, you just need to know the rules
Quaternion.AngleAxis(45, Vector3.forward) produces a 45-degree rotation around the Z axis
call scriptable object -> scriptable object calls static instance coroutine manager -> coroutine managers makes coroutine on itself
Who cares how the underlying math works?
im making a 2d game if you are talking to me
it's still rendered in 3D (:
ohhh
you just have a different camera projection matrix
I wish Unity just called it a Rotation
first rule of quaternions and 4x4 matrices: don’t crack that shit open to look at or modify the actual contents
Quaternion (along with the exposed x/y/z/w values) makes it look frightening
what is even W
is it perhaps similar to this?
💀
Check out those static methods.
so i should make string with the word first?
Unity offers many ways to create and manipulate rotations.
what is a static method ?
you know how complex numbers live in a complex plane, which is 2D? quaternions are like 4D complex numbers. which is why you should NOT look inside them to try to understand
the best way to think of these things is as operators
any method you don't need an actual object to use
oh so basically i should not try to understand quaternions
Quaternion.LookRotation isn't being run on a specific object
it's just..a method, by itself
Most likely, yes
in the score script?
so anything that has transform isnt one right?
you should understand how quaternions work on each other, but you don’t need to understand the inner workings of a quaternion
anything that you call on transform is non-static, yes
How are you showing the score on the canvas?
you are calling a method on your specific Transform object
text
now i dont understand what my problem is and how to solve it
remind me what you doing
the only things you need to know about quaternions is:
- multiply quaternion => rotate the rotations
- they don’t commute
- don’t open them. do not read the x/y/z/w
i came here not knowing the answer and now i dont know the question lmao
Can you be more specific?
i want to rotate the z axis of a "bullet" depending on what bullet it is
@timber tide it gave me a nullreferenceexception on my scriptableobject on the line calling the static instance manager
with this math equation: transform.rotation = Quaternion.Euler(0, 0, explosionScript.amountOfBullets * (360/explosionScript.fireAmount ));
Do you want to make the bullet spin around its local Z axis
or the world Z axis?
whats the difference?
Sounds like you didn't create the instance on the scene
Hello I have here a basic typing effect for a string when it is being displayed with TMP_Text. I want it so that each letter that is type, it will start off with alpha 0 and slowly the alpha will increase to 255/#FF, how would I attempt this? Thank you
The former will make it spin the same way, no matter which way the bullet is facing
so you get the quaternion for the rotation you want to apply (Quaternion.Euler(….)), you get your current rotation quaternion (transform.rotation), you multiply them together, and assign that in
isnt it the smae?
let me make a little demonstration
bam. rotation accomplished
it has text and on the text ui it says Score and other text ui high score i attached the score script to obstacle
Did you debug your code already?
how do i get all that?
oh lol yeah
i now dont even know what i wanted to debug
Thanks a lot!
im just getting bombarded with info way above my level i think
I'm guessing you want the left image.
Quaternion.Euler(…) gives you a quaternion based on whatever euler angles you give it.
transform.rotation is the quaternion for your thing, which you can use to both read and write.
Ah, I understand what you are doing now. My 3D example is not helpful.
i want it to rotate on the blue arrow
Code is in most cases Input => Processing => Output. If your output is not what you expect, then you should check the input and that you're aplying the correct processing to it. Now, break down your code with that in mind and tell me what you need to debug.
You didn't break down anything. What is your input and what is the processing?
my input are numbers and the processing a math equation?
Okay, then did you debug your numbers?
Should've done that like 30 min ago
And... you are replacing by script the text to the current score right?
@swift crag i think the quaternion order is a unity implementation detail. For normal quaternions, it is the order I described (A*B = do B then A). But i guess Unity does it in reverse.
or the documentation is flipped
yes
yes, that appears to be the case
(another reason unity should have just called the damn thing Rotation!)
when i don't start it shows this
i just don’t know why the hell they would implement quaternion multiplaction backwards
Then why are you surprised when the text that you are specifically telling to replace is getting replaced?
but when i start it shows this
but idk, i do all my quaternion multiplication the correct way, so maybe it’s the unity documentation that is backwards
but how do i make the text don't replace only the numbers of the score and highscore
Obviously, you are replacing the default text you wrote for those values
all 6 are the same
so the problem is even b4 the numbers
because it makes way more sense for combining rotations
so its in the for loop inside the coroutine
not really, because rotation operators combine like matrices
As I said just make it a string and add "Score: " and "High score: " first
it just makes it read chronologically instead of mathematically
any ideas how to fix it? i don't understand
in the IEnumerator thing, what does yield mean and return mean? the tutorials just mention their existence
you are telling the text component to display a string
if you string does not start with "Score: ", then you will not see the word "Score"
If you're talking about Coroutines in Unity, It means "pause the code here until <something>" depending on what you yield return
ienumerators do a MoveNext every time you yield. Yield return makes the IEnumerator current value change to that value
foreach (x in IEnumerator y)
basically does:
while (y.MoveNext)
x = y.Current;
Maybe the text doesn't have room, or maybe other code is overwriting it
Or maybe you didn't save your code
interesting
im going to read that 5 more times
so if you do:
Ienumerator MyEnumerator() {
yield return 5;
yield return 3;
Debug.Log(“hi”);
yield break;
then the IEnumerator gives you a 5, then a 3, prints hi, then a break
If a method returns IEnumerator and has a yield instruction, the compiler turns it into a class with fields that keep track of the data in the method's local variables.
So there's no magic at runtime (:
the problem is in the middle of both because inside the for loop the debug log is correct but when getting it from the other script its wrong
yield break makes MoveNext false, which means you’re done
share the entire script. !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
just as loup said b4 it is becuase it take the information once the for loop is completed and therefore they all take the same number
so it waits 5 frames, then 3 frames and then says hi
no
it returns the number 5
then returns the number 3
then prints hi (i changed the code)
then it breaks (done)
Then pass the information to whatever needs it when you still have it.
i see
when you start a coroutine, you're just throwing your enumerator into a list of enumerators. Unity calls MoveNext on each one each frame by default
unity coroutines use IEnumerators, and interpret the things you yield return to know how/when to wait
i dont know how to do that im afraid, or atleast i cant think of how right now
hmm I see what you mean
I see where the problem lies here.
So MeteorFireMovementScript has a Start method.
Do you not know about methods with parameters?
so if your IEnumerator does yield return new WaitForSeconds(5);
and it is a coroutine, then unity will do that, get WaitForSeconds object, it looks in that object and decides to wait for 5 seconds before going on in that IEnumerator
In that method, you check explosionScript.amountOfBullets.
i dont know what you mean by parameters right now
you can use Ienumerators that are not coroutines
Start runs the frame after you create something.
By this point, amountOfBullets is 6. Everyone sees 6 and does the same thing.
Then it's a good time to go over C# basics. You're not gonna get far without understanding it.
but if you start coroutine and give an ienumerator, unity will try to interpret the outputs to try to figure out waiting times or timing etc
Yes. You really need to know some fundamental concepts here.
you can also just make an Ienumerator to give a bunch of numbers, or strings, or whatever
@plush oxide make sense?
my problem is im really bad at words, and i tend to forget the name even if i understand it
oh im reading
ill take like 2 mins and read
ienumerators are used outside of coroutines, and you should know both. IEnumerators are really fucking useful
Well, you can speak English to a degree, that means that you have the capacity to remember words. That's more than enough to learn the C# basics.
i see
im just trying to understand what you meant by It returns 5 then 3
alright
what does returning 5 and 3 actually do
what is considered the basics?
yield return 5; makes the enumerator stop running and sets its Current property to 5
enumerator.MoveNext();
Debug.Log(enumerator.Current); // logs "5"
enumerator.MoveNext();
Debug.Log(enumerator.Current); // logs "3"
You can yield return whatever you want in a method that returns IEnumerator.
IEnumerator<T> requires you to yield return a specific type. It is the generic equivalent to IEnumerator.
im trying to create a object that will always be in the center of the screen that i can track, so like not at (0.0) but at the center of the screen no matter where i move inside a scene, what would that be called? having a hard time finding it by searching up on google/youtube. im having trouble with the boundries in my game tracking the cursor, so i thought maybe having a center object thats connected to the screen that the camera can lock onto thats then moved by the cursor drag might be worth trying
some relevant terms here would be "screen space" or "viewport space"
thank you so much, i will look that up
okay, I guess I got some of that but could you say it in REALLY easy terms
what part do you not understand
i can't help you if you just say "i don't get it"
An enumerator's job is to give you a sequence of values
Well, for starters, understanding types, classes, structs, references, methods, parameters, class members, fields, different scopes, if statements, loops, instances(objects).
Current is the ... current value
do you have an example perhaps
It is part of the IEnumerator interface. Every IEnumerator can tell you the current value
yes, this code is an example
based off of Loup's code
When you implement an IEnumerable and ask for the inner enumerator, Current is one of the properties that exist inside of it. It determines the current value to return, which in the case of a Coroutine would be WaitForSeconds for example, assuming you yielded with this class.
List<int> integers = new() { 1, 2, 3 };
var enumerator = integers.GetEnumerator();
enumerator.MoveNext();
Debug.Log(enumerator.Current); // logs 1
enumerator.MoveNext();
Debug.Log(enumerator.Current); // logs 2
enumerator.MoveNext();
Debug.Log(enumerator.Current); // logs 3
The other important part is MoveNext, which moves to the next value or returns false if there are none left.
Going through all the categories on this website would probably be enough to cover the basics + a bit more:
https://www.w3schools.com/cs/index.php
ill just stop asking questions and wasting your time, because each time someone answers it has another word or something I dont know, so Ill just get to this later i guess
you need to actually tell us which parts you do not know about so that we can tell you about them
"I don't get it" x100 is not useful
okay ty!
we would be here for a while
i will check into that
fair enough
in the SIMPLEST terms possible, in real life terms perhaps, what is an enumerator
how bout we start there
so I can build on it
let me make a thread
oka
I'm trying to make this little app (preferably in unity) where I have two phones, one phone is closed and the other has basic UI with just one button. Whenever I press that button, a notification should appear on the other phone, but i have zero clue 😆
Would I require a server of any kind that uses cloud code to push it?
I'm currently looking at the mobile notification package from Unity, it has like 80% of what I need
ive been trying to trouble shoot this for a bit but no luck. im trying to fix a issue with my game where the game finally respects the boundries i set in so the camera doesnt go past it, but now it keeps jittering between (x,y) and (-x, -y). Any suggestions for the cause?
best to post code so people can help with the issue besides trying to guess
will do, its just because ive already posted it recently and wanted to avoid spamming
here is the script that causes jittering
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
[SerializeField]
GameObject Cursor;
[SerializeField]
float timeOffset;
[SerializeField]
Vector2 posOffset;
[SerializeField]
float leftLimit;
[SerializeField]
float rightLimit;
[SerializeField]
float bottomLimit;
[SerializeField]
float topLimit;
private Vector3 Origin;
private Vector3 Difference;
private Vector3 ResetCamera;
private Vector3 velocity;
private bool drag = false;
void OnDrawGizmos()
{
//draw a box around our camera boundary
Gizmos.color = Color.red;
//top boundry line
Gizmos.DrawLine(new Vector2(leftLimit, topLimit), new Vector2(rightLimit, topLimit));
//right boundry line
Gizmos.DrawLine(new Vector2(rightLimit, topLimit), new Vector2(rightLimit, bottomLimit));
//bottom boundry line
Gizmos.DrawLine(new Vector2(rightLimit, bottomLimit), new Vector2(leftLimit, bottomLimit));
//left boundry line
Gizmos.DrawLine(new Vector2(leftLimit, bottomLimit), new Vector2(leftLimit, topLimit));
}
private void Start()
{
ResetCamera = Camera.main.transform.position;
}
void Update()
{
//cameras current position
Vector3 startPos = transform.position;
//Players current position
Vector3 endPos = Cursor.transform.position;
endPos.x += posOffset.x;
endPos.y += posOffset.y;
endPos.z = -10;
//smoothly move the camera towards the players position
transform.position = Vector3.Lerp(startPos, endPos, timeOffset * Time.deltaTime);
transform.position = endPos;
transform.position = new Vector3
(
Mathf.Clamp(transform.position.y, leftLimit, rightLimit),
Mathf.Clamp(transform.position.y, leftLimit, rightLimit),
transform.position.z
);
}
private void LateUpdate()
{
Vector3 pos = transform.position;
pos.z = -10;
transform.position = pos;
if (Input.GetMouseButton(0))
{
Difference = (Camera.main.ScreenToWorldPoint(Input.mousePosition)) - Camera.main.transform.position;
if(drag == false)
{
drag = true;
Origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
else
{
drag = false;
}
if (drag)
{
Camera.main.transform.position = Origin - Difference * 0.5f;
Camera.main.transform.position = Origin - Difference;
Camera.main.transform.position = new Vector3();
// Mathf.Clamp(transform.position.x, leftLimit, rightLimit);
// Mathf.Clamp(transform.position.y, bottomLimit, topLimit);
}
if (Input.GetMouseButton(1))
Camera.main.transform.position = ResetCamera;
}
}
You can share your code, but if you're trying to do bounds, you can achieve that with cinemachine and the confiner:
https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/manual/CinemachineConfiner.html
also bounds class if not using cinemachine
i tried using cinemachine but for some reason i couldnt make it work, so i kept looking and found a tutorial on youtube that seemed to be applicable for my code. i could try and use it again because if i can make it work it would prop be way easier. ive used like two days on thisssss lmaoooo
I'm confused why you need lateupdate here at all, if you're moving your camera in Update and already clamping it to the left/right limit? Also your clamping of the transform is using the y value for both x and y.
ive been following guides and tried to understand how the code works, im still not too sure on the difference between late update and update but this is how atlest 1 portion of the code in this script was set up. this is like my first experince with real coding and game making so im trying to learn as much as i can lol.
so if i understand correctly i should remove late update and put its contents under update? oh shit yeah thanks i completly overlooked that! thanks!!
just a quick question when adding aiming is it best to use an animation for aiming or just like moving the object with code?
If you're trying to do something like, have your character aim where you mouse is, you would use Inverse Kinematics for your arms and maybe head.
If you're referring to having just a standard aim, you could just animate it.
It's hard to say specifically what you should do because there's lots of ways to do the same thing. But it just stood out to me that you're already clamping in update, so I'm not sure what the purpose of late update here is.
Personally, I'd just use cinemachine for this (and what I've done myself)
thanks aiming isnt realy like such a big thing in my game so i will just use animation thanks
np
Update vs. Late Update
You could imagine it like a drive through to order food, 1 car is 1 frame. Late Update happens at the last window where you pick up your food. Also, I'm very hungry, and was thinking about what to eat 😅

well, it's doing good so far
and right now it have tutorial boards
i also made a parkour part where you have to run over the holes since you can't jump over them because of the platforms above
anyone could help?
Where can I find those settings? I can't find it inside Player settings
not a code question. did you try the search bar in the Player Settings?
Yes, ther is nothing highligthet
need a bit more context on the problem you're trying to solve here
I can't get a sound. But it is shown in the master that something is playing
On Mobile
where did you find this "fix" though
also are you trying to test on mobile how ?
Why would it? You don't have anything anywhere that adds 5 seconds to the timer. Maybe show where you're trying to do that and we can try to see why it doesn't
Is there a way to change the name of element 0, element 1....?
iirc if the first field is a string it does show
^ or a custom editor/property drawer
public string name on the elements
is not working
so FuncionesProcesos is the type of the list displayed here?
Did you actually set any of their names?
I think no
then that's why
it will take on whatever name you give
also pretty sure it should be called name not Name but not sure if that makes a difference
Hello. I know that this should cause unity to crash because it's an infinite loop but it doesn't.
Instead, it continues counting and the game runs normal.
I'm confused on why this is the case.
yeah thats how coroutines and yield return null works
It doesn't because you are doing yield return null; which means "Pause here, come back to me next frame".
During that pause, the rest of the game engine is able to do its thing
whereas a loop without that would not allow the rest of the game engine to run between iterations
ohh
So what if I want to freeze the game while the conditions aren't met?
Let's say until SkillQueueNumber is more than or equal to 10 perhaps
That's silly because you could then replace all of this code with:
int SkillQueueNumber = 10;```
Although actually your code as written in this screenshot will simply never enter the loop
like this?
oh silly me
also there's no reason for this to be a coroutine now
since it isn't doing any yielding
This is just a simple example I'd like to be explained
well in this code you make a variable, set it to zero.
Then the while loop checks if 0 > 10, and it's not, so it skips the loop
Then the function ends
this all happens immediately
because before I thought that if you put "true" on the while condition, it would be an infinite loop and crash the game
Yes if you do that without a yield inside, that will happen
if you did that now, it will
but, as Praetor says, without a yield actually breaking processing there is no need for it to be a Coroutine
I have an object that I want to animate just once. What's the easiest way to do that?
This was the original code and I was wondering why it prematurely stops without fulfilling any of the conditions
set up your state machine to transition to the Exit node after the animation
which conditions is it not fulfilling?
But anyways, thank you all for the help
@west sonnet uncheck the looping and it will play only once
If you want to, you can always attach the debugger and step through the code
and see what's going on
The queue.length one
But I want to start it via a script
wdym by "it's not fulfilling" the condition? Add some Debug.Logs to see what's going on
but yeah, yield shouldnt be there
that code is so bad for many reasons
For some reason in Unity, you can't just do Animation.Play()?
if you don't want a yield there, there's no reason for this to be a coroutine
You can, if you're using an Animation component
(the legacy one)
@west sonnet set it not to loop and then enable animator component from script
Can also use it with the animator to force play an animation state in your animator controller
You also can yes call Animator.Play https://docs.unity3d.com/ScriptReference/Animator.Play.html
It's supposed to go through all the elements in the array then stop whichever element is not null
I'm sorry 😔
but yeah this code is scuffed
for one, it seems to think arrays are 1-indexed instead of 0-indexed?
for two, there's no handling for the case when there are no skills available in any slot
In that case, the loop will go on infinitely
think what happens if all entries are null
thanks for pointing that out
I didnt think of that
I guess it should check whether at least one of the slots has a skill?
is that right?
Which way can i make a bullet which i can change the speed even after it's been spawned?
I guess I just don't really understand why you would use a while loop here
a for loop would do just fine
and be less risky
I can only using animation.play() if I change the animation to legacy?
yes
because i see most people use things like adding force to rigidbodys, but i want to be able to add or remove force while it's in movement
you can do it with either
but you will need to provide the parameter with either one
By... writing code that does it.
What makes you think force can't be added while it's moving?
Hi guys, quick question.
Im trying to make a very simple main menu with Ui button, when the button is clicked music fades out and scene is switched. However the scene does switch after some time but for some reason the music doesnt fade out. Why could that be?
public AudioSource MenuMusic;
public void StartShift()
{
StartCoroutine(PlayGamee());
}
public IEnumerator PlayGamee()
{
MenuMusic.volume = 90;
yield return new WaitForSeconds(0.5f);
MenuMusic.volume = 80;
yield return new WaitForSeconds(0.5f);
MenuMusic.volume = 70;
yield return new WaitForSeconds(0.5f);
MenuMusic.volume = 60;
yield return new WaitForSeconds(0.5f);
MenuMusic.volume = 50;
yield return new WaitForSeconds(0.5f);
MenuMusic.volume = 40;
yield return new WaitForSeconds(0.5f);
MenuMusic.volume = 30;
yield return new WaitForSeconds(0.5f);
MenuMusic.volume = 20;
yield return new WaitForSeconds(0.5f);
MenuMusic.volume = 10;
yield return new WaitForSeconds(0.5f);
MenuMusic.volume = 0;
SceneManager.LoadSceneAsync(1);
}
Read the docs for volume
Values of 90 etc don't make any sense
I just want it to stop when it finds something that isnt null
Oh. That explains it, I feel like an idiot now. I've been trying to fix this for like an hour now and nothing helped.
Also, make it a loop please
Yeah but i mean i dont know how to make it like RBforce (obviously a example) = 500f and not Rbforce * 500f
Yes you can do that, in a for loop
and I think that using a while loop would be the easiest
So to my understand im supposed to do
1 then 0.9f and so on?
It sounds to me like you're confusing forces with velocity
kinda
rigidbody.velocity =
yes
would directly set the rigidbodies velocity
Velocity is a property, you can set it directly to whatever you want https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
how can i make it stop? I'm thinking putting it inside an if statement or something
Alright, thanks!
while volume > 0
sure but this manually writing of all of them is kinda silly, you should just use a loop and change it every frame not every half second
then when its not.. loop ends
Like I said, a for loop
you literally just write a basic for loop that goes over the array once
Im trying to learn IEnumerators since i've never used them before so thats why i wrote it like that at first. Later on im gonna try to add some Float fade out duration, so that it calculates automaticly
but how do I get the next available skill?
Isn't that the whole point of the loop?
yeah but that makes me not be able to add velocity like forward
Why do you think that?
Of course you can
you can do whatever you'd like
Because it says X Y Z, not like the addforce
what?
Like in addforce you can add forward
Addforce takes a vector as well
Ok and with velocity you can set a velocity that is "forward"
Wait, are you writing rb.velocity.x =
?
Oh thank you, i will test
For the record, there is literally nothing you can do with AddForce that can't be done by setting velocity and vice versa. They are two differently shaped handles that ultimately do the same thing
The only end-result of calling AddForce is that the velocity of the body changes
Sorry I'm kinda stumped. I'll just use a for loop to check if the whole array is empty and a while loop to get the next available skill.
You only need one loop
You are overcomplicating it
write a single for loop that iterates over the array and finds the first available skill it sees.
My Visual Studio seems to be bugged or something now
yesterday it worked just fine with unity but now it doesn't detects errors
Regenerate project files in the external tools menu
But what if I want to start at the second element and the only other element in the array is in the first?
that's a simple manipulation of the indices in the loop
But what would be forward? Sorry for overask since i dont understand too much about rigidbodys
because in AddForce you can do transform.forward
but you cant in velocity
e.g. cs int startingIndex = whatever; for (int i = 0; i < myArray.Length; i++) { int effectiveIndex = (i + startingIndex) % myArray.Length; var element = myArray[effectiveIndex]; }
yes you can
transform.forward or rb.rotation * Vector3.forward
what makes you think that?
you are making stuff up!
When i tried it said transform.forward dint exist
you did something wrong, unrelated to AddForce and velocity
show your code
and your error
transform.forward exists so long as the code you're writing is in a MonoBehaviour derived class
if not, that has nothing to do with AddForce and velocity, it's a whole separate issue.
why are you writing new Vector3(transform.forward, 0, 0)??
that is not the error you said it was
it's an error because your code is nonsense
transform.forward is a Vector3 you are using it wrong
rb.velocity = transform.forward
remember it's new Vector3(x, y, z) not new Vector3(anEntireVector3, y, z)
Well i mean that was what i saw from the unity doc
no it is not
You copied it incorrectly
show where the unity docs have that
wow it's been a while and I still can't fully understand this, I don't think I'll be writing code of this level anytime soon.
Thanks!
Notice how that doc doesn't have a whole ass vector inside a vector
Ok and do you see new Vector3(transform.forward, 0, 0) there? No.
I think what you're missing here is that velocity accepts ANY Vector3. Doesn't matter where it comes from. So you have many options there. You can:
- Create a new one with
new Vector3 - Use one from another place or something such as
transform.forward
But new Vector3(transform.forward, 0, 0) itself just does not make any sense, because transform.forward is not a number you can plug into x in the x, y, z of a Vector3, it's a whole vector itself.
Well i dint know that
instead of parking your car in the garage, you're trying to park the car in itself
Let's say you have a garage with 3 spaces for cars. Instead of putting 3 cars in your garage, you're trying to put another whole 3 car garage in one of the 3 spaces 😭
Am I doing something wrong here? My animation isn't playing
Do you have an animation state named "Base Layer.+1 Pizza"
Anything in the console?
This, right?
No
That is an animation in the base layer named "+1 Pizza". There's nothing named "Base Layer.+1 Pizza"
Consider checking the documentation for .Play to see how layers are used:
https://docs.unity3d.com/ScriptReference/Animator.Play.html
The example code does suggest you can do that...
although it also provides an explicit layer ID
Is the code even running?
note that you're already in that animator state
Wouldn't it play when the game is started then? Which it isn't
In the example, it's writted "Base Layer.Bounce"
Hence why I also put Base Layer
i would start by making sure that:
- the animator is doing anything at all
- your code is even running
Yeah I just noticed that. That's... odd. They still provide the layer as a number, which is how you'd play an animation in a specific layer, I don't know why they also put the layer name on it? But I think the issue is in what Fen's saying.
I have seen that syntax before, where you specify both the layer name and the state name
I don't use the Animator much so I don't know too much there
My code is running. Everything else in the same method works just fine. I don't see any activity in the animator tho, not sure why
Do I need to create a seperate empty state so that I can transition from the empty state into the animation?
You would want that, yes
What am I doing wrong now? If I press B, nothing happens
The trigger isn't enabled in the animator
Is your code running?
Yeah, I've confirmed with Debug.Log
Where did you put the log
Just below the anim.SetTrigger, so the Debug.Log happened when I pressed B
Then either:
- You will see an error in the console about the trigger not existing (or some other error)
- the trigger is being set
But I'm not getting either of those, nothing is happeniing
The bottom one is happening if you aren't getting an error
show screenshots of things
maybe:
- Your state machine is not set up to do anything with the trigger
- Your state machine is reverting to another state quickly
- You have error logs disabled in your console
- You're looking at the wrong animator
These are all possiblities
PizzaGained trigger is enabled in screenshot because I manually enabled it with mouse click
but it's not normally enabled
which object do you have selected?
Are you selecting the animator that's actually in the scene?
shufflee is a List<T>. Am I correct in thinking that this code will set shufflee to be a shallow copy of what it previously referred to? Or is there a better way to do it?
you are correct. it's a new List object containing the same elements
thanks
Does anyone have any links to any references i can use for not using Update() / fixed update() for movement and the sort.
So using WASD to move around, and each input calling its selected movement method, so W for Forward as an example.
Cause far as i know from Unreal constantly using Update is somewhat a no no, but not sure if Unity is different in that regard.
I've been searching around for any videos, scripting manuals that could help me and so far just been a brick wall, as each thing i've found just makes use of Update.
there's nothing wrong with using Update when you need to, and for the most part you will need to use Update for movement, just maybe not polling each key individually. if you use the input manager look into using the GetAxis methods. if you use the input system you can use events to react to changes in input which will clean up your Update and FixedUpdate methods significantly
new input system is based on events so you can use that, but there is nothing wrong with polling for inputs in update though
Alright, cheers for the information, many thanks.
I'll give this input system a look and take it in forward that its not wrong to use Update.
Cheers again
rigidbody.AddForce(Vector3.up * 500);
doesnt work to make player jump
i tried everything (with code and rigidbody in inspector)
you're likely overwriting velocity somewhere
i have another script for movement
maybe that
probably
it worked, thanks
might not be a bad idea to not subtract and add to the timer in the same method
Hello.
I am having a terrible time of trying to make my play rotation function work in a way that looks good. The attached video, in the later half, shows a jitter when I am holding a directional input, moving the player, and rotating the camera at the same time.
The following is the function, HandleRotation(), that I call in fixed update. My inputs are assigned in update. The player's rigidbody is not kinematic and has interpolation on.
If anyone can help me I would greatly appreciate it. The function does work I suppose. But it looks quite ugly when I'm rotating the camera while moving the character.
{
Vector3 _targetDirection = Vector3.zero;
_targetDirection = _cameraTransform.forward * _playerInputManager._verticalInput;
_targetDirection = _targetDirection + _cameraTransform.right * _playerInputManager._horizontalInput;
_targetDirection.Normalize();
_targetDirection.y = 0;
if (_targetDirection == Vector3.zero)
_targetDirection = transform.forward;
Quaternion _targetRotation = Quaternion.LookRotation(_targetDirection);
Quaternion _playerRotation = Quaternion.Slerp(transform.rotation, _targetRotation, _rotationSpeed * Time.deltaTime);
transform.rotation = _playerRotation;
}```
if you are using rigidbody you should not be using transform, use the rigidbody equivalents
private void UpdateTimer()
{
timer -= decrementSpeed * Time.deltaTime; // decrement timer each time the method is called
if (timer > 0) // if the timer is still greater than 0
{
// log the time and set the color
timerText.text = $"Time: {timer:F1} seconds"; // string interpolation to add time variable inside string
timerText.color = timer <= 10 ? Color.red : Color.white; // ternary operator to set color w/o bulky if/else
}
else
{
// timer is 0 or less
Debug.Log("Time's up!");
Respawn();
timerText.enabled = false;
}
}```
here's how i would do it 🆓 🐝
i just wanted to refactor some code to get my brain working today 😄
dam
Why is this recommended? I applied the rotation to the rigidbody and I am having the same issue.
because when you apply values to the rigidbody the transform is told about it, vice versa is not the case
I see. I'll keep this in mind. Thank you.
It's probably due to using slerp with the 3rd paramter just being a small value. Maybe you want RotateTowards, which your 3rd parameter would make sense for
transform and rigidbody both modify the transform of the object
rigidbody does so via physics engine. transform does not.
so if you change transform, then rigidbody API will fight you over it
also doing Slerp(current, final, t) rather than Slerp(start,final, %)
in general, if you have a rigidbody, you should try to only move your object via the rigidbody commands
if you do not, then the transform is the only thing to mess with
https://unity.huh.how/lerp/wrong-lerp
This is what we mean by the lerp also
if your rigidbody is kinematic mode, then I would try MoveRotation.
if it is dynamic, then you’re basically applying a bunch of torque/forces to try to rotate it, and it will be more difficult to get a specific rotation
anyone know any script ideas how to make when obstacle respawns it would add 20 seconds to the timer?
its pretty tame stuff
Which part do you struggle with?
start small, build up
make a system to control timer. make a system to respawn obstacle. then make them communicate
addvalue i don't understand how to make to add value 20 to the text timer ui
Have a numerable variable, which updates the text
value += 20;
text.SetText(value.ToString());
Your timer isnt UI. It's a number, a float most likely. Your UI should be updating based on this float, not trying to update the UI directly
"add value 20 to the text"
you probably want to add it to a variable and display that instead
Respawn();
{
// respawn logic
// add time to timer
timer += 20f;
}
timer still counting down..
and the else statement will run once more after getting below 0
public class UniqueID : MonoBehaviour
{
[SerializeField]
private string uniqueID;
public string ID => uniqueID;
private void Awake()
{
if (string.IsNullOrEmpty(uniqueID))
{
uniqueID = System.Guid.NewGuid().ToString();
}
}
private void OnValidate()
{
if (string.IsNullOrEmpty(uniqueID))
{
uniqueID = System.Guid.NewGuid().ToString();
}
}
private void Reset()
{
uniqueID = System.Guid.NewGuid().ToString();
}
}``` Hi how can i get this to work on prefabs duplicates please
It is working, but just not doing what you want because the string is only being checked for null or empty.
You need some other way of checking what IDs already exist like a dictionary. Trying to do this automatically will be more of a pain imo than just having some button you can press to assign it a new ID.
the script might be working but the text doesn't even update when obstacle respawns
well which method/condition do you have to update UI ?
i use Updatetimer to update ui
and when do you call Updatetimer ?
i think this might be issue InvokeRepeating("UpdateTimer", 0f, 1f); // update timer every second
i call it at start
and you certain this is running when you do += 20 ?
