#💻┃code-beginner
1 messages · Page 494 of 1
yes
@tulip nimbus any chance you can get a video of what it's currently doing?
no, 748 times
my point is that you can make good arguments for 2D cameras to just do them custom.
but writing your own camera from scratch for 3D? fuck that
Have you changed the timescale anywhere
Not that I know of. Only thing I can come up with is that I deleted * Time.deltaTime in my movement script but that shouldn't apply right
Add Time.TimeScale to your log, see what it is
i’d also search Time.TimeScale via IDE to know if you’re messing with it
Okay for a bit more context if you dont mind me still asking this:
There is a prefab which is called. The shown code is in its Awake() function. So everytime the prefab is created(like a bullet) it aims at the cursor once, and then the prefab travels towards the position it got at the moment it got Instantiated.
However, as stated, they all aim And only then at the Plane Camera when i give it the "Main Cam" tag
yeah ill record one one sec
It's 0
Again thanks for your help, patience and time
Then that's the problem. A time scale of 0 means deltaTime is always 0
You can use unscaledDeltaTime instead, or find where you're setting it to 0 and just not do that
since it seems like you never intended to
That's to be expected, Cinemachine will move that camera to the location of the virtual camera when it's active. It might just be that Awake is happening for them before Cinemachine's? Try putting it in Start. The test I was running had that code in Update and it was working as expected
your game over sets it to 0 😄
Aha! It's the game over script
just as a suggestion by the way, for stuff like "animating" volume over time there are good "tweening" libraries out there, they are convenient (BUT not always the best performance wise)
https://youtu.be/dXOFcdhJx8g
(Theres some loud Bullet sounds so you might want to mute the Video)
(Lets hope you can send YT links since i dont have Nitro)
I put it in the Update function and it works like this.
The Plane is in the "follow" space inside the Cinemachiene Virtual Camera component
Thanks digiholic and sidia. I'll find another way to prevent stuff from happening in the background.
Prob just disable enemy updates
Can you show the inspector of the virtual camera?
I don't think the virtual camera needs the main camera tag but I also don't think that would affect anything since it doesn't have a camera component on it
oh yeah i also gave it the tag but it didnt change much :(
timescale to 0 is fine, unscaledDeltaTime is your friend here
Just a sanity check - the bullets "forward" direction is up, right? The green arrow?
Maybe it is facing the mouse, but the wrong side of it?
No, I mean the sprite you're using. You're angling the green arrow towards the mouse
Can you show the inspector of a bullet with the transform gizmo visible?
like this?
In the scene too, to see where the arrow is
he may be using global gizmos
unless they are always local (i think it defaults to global)
Right, make sure you're on local.
im so sorry if this isnt right. ITs like this on local and global
Okay, so that's the correct orientation...
your on local and global?
what how
It's facing world up
i have an itch that the solution is really simple and im just not showig you guys the right things haha
so they're the same right now
in both global and local its like this
oh, then your good
Let me try to construct a scene as close to what you have as I can and see
cant i send you my project somehow?
or parts of it
It'd probably be faster for me to just rebuild it
i dont want you to download anything but perhaps there is a function to share or smth
then you cant
I have it mostly done, I just need to have the cinemachine camera follow something
yeah you guys are the pros here haha
https://gdl.space/napohujogi.cpp
I think these are the 2 scripts.
thats flattering but you dont need to say that 😅
Thanks man. This finally fixed it!
Yeah, with the camera following an object, and the script you've shown put in Update on a sprite, orthographic camera, using cinemachine, I'm getting exactly what you'd expect, the arrow faces the mouse cursor even as the circle moves. There is definitely something else going on here. Can you share the full script for the bullet?
Ah, the screenshot didn't include the cursor, but it's pointing at the cursor and not the circle
void Update()
{
FaceMouse();
}
void FaceMouse()
{
Vector2 mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector2 direction = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
transform.up = direction;
}
This is basically all the code, i replaced it to this again, before the big part was in the Update function since i wanted to put some other stuff there but it works the same ig
Can you show the inspector of the plane object?
It looks like your bullets are facing the plane, rather than the mouse
What scripting (C#) tutorial do you guys reccomend? English isnt my first language so keep that in mind.
Eh, let's see the !code for Plane Behaviour as well. Maybe it's doing some shenanigans to the prefab that's affecting all of the children of it? I'm not sure what but at this point all the things I've expected it to be have all been fine so I'm gonna just check everything
📃 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.
What scripting (C#) tutorial do you guys reccomend? English isnt my first language so keep that in mind.
Idk your level but As a beginner "Brackeys" on YT. His main language also isnt english so he explains it pretty simple imo
But as i can imagine you heard that before i can also greatly recommend: Code Monkey and this Video: https://www.youtube.com/watch?v=GhQdlIFylQ8&t=5785s
This course will give you a full introduction into all of the core concepts in C# (aka C Sharp). Follow along with the course and you'll be a C# programmer in no time!
⭐️ Contents ⭐️
⌨️ (0:00:00) Introduction
⌨️ (0:01:18) Installation & Setup
⌨️ (0:05:03) Drawing a Shape
⌨️ (0:17:23) Variables
⌨️ (0:30:06) Data Types
⌨️ (0:37:17) Working With S...
Probably !learn but I can only vouch for the english-ness of it
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks!
Dont laugh if you see the code tho hahaha. Ill send it one sec
At this point I'm too baffled to be snarky
I just wanna see what's going on with this tbh
oops
void Update()
{
//CONTROLLS
if (Input.GetKey(KeyCode.A))
{
dir = 0.05f * TurnSpeed;
}
else if (Input.GetKey(KeyCode.D))
{
dir = -0.05f * TurnSpeed;
}
else
{
dir = 0;
}
//FUEL BOOST
if (Input.GetKey(KeyCode.LeftShift) && boosterFuel > 0)
{
MoveSpeed = BoostSpeed;
boosterFuel -= 1;
}
else
{
MoveSpeed = CurrentdefaultMoveSpeed;
boosterFuel += 1;
}
//SHOOTING CONTROLL
if (Input.GetKey(KeyCode.Mouse0) && Ammo > 0)
{
shootDelayGun1 -= Time.deltaTime;
if (Gun1 == true && shootDelayGun1 <= 0)
{
shootDelayGun1 = Gun1shootspeed;
Audio_Source.PlayOneShot(ShootGun1);
ShotGun1();
}
}
else
{
shootDelayGun1 = Gun1shootspeed;
}
//Passive Movement
transform.position += transform.right * MoveSpeed * Time.deltaTime;
//Turns
transform.Rotate(0, 0, dir);
}
void ShotGun1()
{
Instantiate(BangVX, transform.position, Quaternion.identity);
Instantiate(BulletGun1, transform.position,Quaternion.identity);
}
I havent checked out IEnumerators and Invokes so i still used simple Variables and time.Deltatime for my seconds
Send it in a pastebin, under "Large code blocks"
!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.
I can't Ctrl+F a discord message or a screenshot
https://hastebin.com/share/urulemecak.csharp
This is the ENTIRE code now with the variables
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
@deft grail @polar acorn I see...
Okay, everything checks out. Nothing's changing a property on the bullets, nothing's messing with the camera
Have I looked at the inspector for the main camera yet?
Unsure if I've asked for that
ITS 4 HOURS?
im curious now, try clicking on game view while in game
just to test something
your not gonna learn coding in 4 minutes
i cant watch the entire thing in just one go]
i gotta split it up
then in sections
ok
thought the same when i started a few weeks ago but when you follow the steps and listen time goes by fast
Ah! Projection - Perspective. You said it was 2D so I've been using Orthographic
do you want me to record it?
you started a few weeks ago?
now u understand it completely?
Not at all hahaha
Yeah, it's a bit short but it might get you going as a quick primer.
"bit short'' i gotta school, homework, my own job
and screen time
take will take me weeks to watch
best get crackin
Yes. Four hours for an intro to coding is short.
It's not something you just know after 20 minutes
nothing really it stays the same, but digiholic had the solution
It's a skill that will take literal years to progress
Is it behaving now? Was that the issue?
we have a over 700 hours of coding !learn
You honestly need to earn a medal for that
That was it
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
!idonthavetimehelpme
Yeah, a perspective camera has the mouse at the position of the camera. It won't actually be able to detect the mouse movement
😭
it'll always be at the same spot, where the perspective converges
you'd need to manually offset the mouse position to use perspective, but for a 2D game you probably want orthographic anyway
There is no solution that would be faster than learning
why would you need unity pro
At no point has anyone suggested anything that costs money
also why would you spend all of your money on a phone
On a phone
yes
@queen adder We don't need the life story, nor do you need Unity Pro.
hah
and some overclocking
None of this is relevant
How you choose to waste your money is irrelevant to the time it takes to learn to code
why cant i say the word ''k''
It was really really demotivating for me when i started. Im lucky because i have alot of time on my hands currently since i just graduated.
Even if you do a bit every day and if you dont give up it adds up.
The start was the hardest part. I also recommend learning by just doing. You get faster and better over this time even if its just a little. Plus it is productive. When it comes to coding you NEVER stop learning and you can always improve. The hard part is always starting. But even when you have little time you will thank youself that you started.
im still a beginner but i learned so much by just doing this current project and asking people that really know
for me it is
you see the problem here
How
what is it? just curious
it took me 3 years for common english language
mongolian
I have a solid grasp of code fundamentals (statements, variables, functions) when it comes to interacting with unity.
But I struggle with code architecture and understanding "higher level" OOP concepts such as classes, singletons, serialization.
any suggestions for resources that might help?
Here's a decent blog post about singletons at least: https://gamedevbeginner.com/singletons-in-unity-the-right-way/
Thats intresting and i see the problem that there are not many tutorials in mongolian (if any) on programming. Maybe just follow what the people in the tutorial are doing for now. Programming (in my opinion) is alot more about logic than english. So if you know what each code block does and you can learn to combine them
English also isnt my first language but i learned it by watching youtube and taking courses and i got better
true, most videos youtube arent allowed in mongolia
Im not saying you should pay to improve tho
If you can access the unity website, you can access !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Seems more like you just don't have internet, rather than it being blocked
¯_(ツ)_/¯
Then I guess you'll just have to figure it out from the documentation
If you physically cannot access the websites then there's nothing we can really do here
bypassing the law in mongolia can get me to jail
so im not taking any risks
Then there's nothing we can do
there are almost zero Mongolian coders
most people in mongolia get their jobs of their parents
does this work for you?
and there isnt really a mongolian scripting family
Wi-fi connection doesn't mean that Wi-fi device has internet access. Also most of this is off-topic to the channel.
If you can open the Unity API and other libraries containing information about Unity, the best way is to just code and try anything. Its hard but i beliebe this is the only way
sorry we lost topic
i did use a banned way of getting unity software
a imported usb
lets go to off-topic
yeah
There is no off topic. Take it to DMs.
@tulip nimbus ive gotta eat
yeah, no worries ill send you a few DMs
what is a field offset?
Then you're probably entirely out of luck
hey I think my VSC is broken. Its not showing any red squigglies and its also not suggesting autocompletion things like functions of a class and whatnot. I tried looking up stuff for intellisense cuz I think thats the right area but still not working. Anyone got any help ?
Here's the config guide:
!vscode
Other than that I'm not sure, it hasn't broken for me in a long time
First I'd try restarting vscode and unity
public virtual void Attack(Microorganism target, Vector3 knockbackDirection)
{
target.GetDamaged(Damage);
Debug.Log(Health);
if (KnockbackActive)
{
Rigidbody targetRb = target.transform.GetComponent<Rigidbody>();
ApplyKnockback(targetRb, knockbackDirection);
KnockbackActive = false;
StartCoroutine(KnockbackCooldown(targetRb, KnockbackTime));
}
}
private IEnumerator KnockbackCooldown(Rigidbody rb, float knockbackTime)
{
yield return new WaitForSeconds(knockbackTime);
KnockbackActive = true;
if (rb.transform.GetComponent<NavMeshAgent>() != null)
{
rb.transform.GetComponent<NavMeshAgent>().isStopped = false;
rb.transform.GetComponent<NavMeshAgent>().updatePosition = true;
}
}
private void ApplyKnockback(Rigidbody rb, Vector3 knockbackDirection)
{
if(rb.transform.GetComponent<NavMeshAgent>() != null)
{
rb.transform.GetComponent<NavMeshAgent>().isStopped = true;
rb.transform.GetComponent<NavMeshAgent>().updatePosition = false;
}
rb.isKinematic = false;
rb.AddForce(knockbackDirection * 1500f);
}
public class Hurtbox : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Hitbox"))
{
Microorganism target = other.transform.parent.GetComponent<Microorganism>();
if(target != null)
{
Vector3 oppositeDirection = (target.transform.position - transform.position).normalized;
target.Attack(this.transform.parent.GetComponent<Microorganism>(), oppositeDirection);
}
}
}
}
Hello everyone, I have this class which holds some methods used by my player and my enemies. Each element holds a hurtbox and a hitbox.
The thing is that my enemies are controlled by a navmesh and their rigidbody is kinematic. And when trying to apply a knockback, it gets pretty buggy, even disabling the path following and making it dynamic.
Is there any efficient way to handle knockback with navmesh controlled elements?
tyy! it worked
Nevermind. Got it working.
Btw, if you want cleaner and slightly more performant code, I suggest caching the NavMeshAgent in a variable instead of calling GetComponent multiple times
Either a class member variable or at least replace this:cs if (rb.transform.GetComponent<NavMeshAgent>() != null) { rb.transform.GetComponent<NavMeshAgent>().isStopped = false; rb.transform.GetComponent<NavMeshAgent>().updatePosition = true; }
With this:cs if(rb.TryGetComponent(out NavMeshAgent agent)) { /* agent.thisAndThat */ }
(The .transform is redundant too)
hey guys, 2 questions here. first, why is my animation not speeding up even tho i made it faster and also why is my enemy not displaying a particle when struck?
How did you make the anim faster?
As for the second question, no one can answer that without seeing code etc.
I see. I'm gonna apply it. Tysm.
i just sped it up the actual anim and tried to increase speed in animator
What does "I just sped it up" mean
i made the actual anim shorter
Scaled the animation keyframes horizontally, I assume
yeah that
Show the inspector of the animation state in #🏃┃animation , it doesn't seem like a code issue
Note: Animation state, not animation
okay, for my 2nd one ill paste code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollisionDetection : MonoBehaviour
{
public WeaponController wp;
public GameObject HitParticle;
private void OnTriggerEnter(Collider other)
{
Debug.Log(other.name);
// Use IsAttacking instead of isAttacking
if (other.tag == "Enemy" && wp.IsAttacking)
{
other.GetComponent<Animator>().SetTrigger("Hit");
Instantiate(HitParticle, new Vector3(other.transform.position.x, transform.position.y, other.transform.position.z), other.transform.rotation);
}
}
}
Psst, use "inline code" from this bot message: !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.
goyt it will do next time
You could edit your previous message
Anyways, does the Debug.Log ever log anything?
nope
Are you using 3D or 2D colliders/rigidbodies?
rigidbody and capsule collider for player and box collider for enemy
will do
I have this code:
private void Update()
{
mouseX = Input.GetAxis("Mouse X") * mouseSens * Time.deltaTime;
mouseY = Input.GetAxis("Mouse Y") * mouseSens * Time.deltaTime;
transform.rotation *= Quaternion.Euler(0, mouseX, 0);
camRotation -= mouseY;
Mathf.Clamp(camRotation, -90f, 90f);
mainCamera.transform.rotation = Quaternion.Euler(camRotation, 0, 0);
}
But the Mathf.Clamp() is not clamping. The camera just rotates past 90degrees I cant figure out why
you arent actually clamping
your doing nothing with the result
oh you are right
Also don't multiply mouse input with Time.deltaTime or it will be inconsistent
Mouse delta is already framerate independent
So just use mouseSens?
Thanks btw sometime i am just stupid
Yeah, but make sure to make mouseSens about 50-100x smaller after removing thet deltatime multiplication
aight thanks :D
NullReferenceException: Object reference not set to an instance of an object
Which line?
The most common error you will see.
tried the different ones and im getting this error
very easy to find the cause too. Double-click on the error @vagrant fjord
takes you to the place it happens. Usually isn't too hard to figure out why.
that's the object ono which it's happening
the error will also contain a filename and line of code
you need to look there
i downloaded the enemy from asset store i think its that
its super confusing and i might just try it on a cube
You're throwing your hands up and giving up
you can figure out the error and fix it
it's not hard
you just have to try
i got no clue bro but ill try
Follow the advice being given, we are showing you how #💻┃code-beginner message
for some reason when I reference the DirectionsList it says "Cannot implicitly convert type 'LaserMoveIn.DirectionsList' to 'bool'"
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
on what line
if (direction = DirectionsList.Right)```
you used =
instead of ==
= is assignment
so it's returning what you assigned, and then trying to use that as a bool
omg im so stupid this is like the third time
DirectionsList is not a bool
It's not like i'm new to proggraming or something, I used to use python so much, but I still make this mistake SOOOOO much 😭
lol it used to happen with me too 
i tried and i got no clue, followed everything
(Graph) is the thing that showed up when i double clicked
Oh, that's just a Unity UI bug
Probably Definitely from the Animator window
Reset your layout, should fix it
Window > Layouts > Default
thanks!
Np - next time show the full error
We assumed it was from your own code but it was Unity's
just restarted: error gone but still not working?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
sorry my bad
its about multiplayer
i want to know how to start
but first want to know what it is actually
"multiplayer" is quite vague
Multiplayer just means a game with more than one human player.
yes i know
i heard that servers are costy
Why are you jumping to "servers are costly"
You can make it peer to peer or use distributed authority
dedicated servers are not the only option
btw #archived-networking exists
like what is the difference between dedicated server, server hosting, multiple server hosting and peer to peer connection
its more ummm coding related like server programming
so i thought this place would be ok
my bad
can we port over?
What is not working? Whatever it is, it's not related to the previous GraphView error
how do i play an animation clip in code? like
if (input.getkey(keycode.e)) {
animClip.Play();
}
something like that
With an Animator- you set properties on the animator to trigger the state machine into doing things
Hello good people, I'm having great troubles, and have been struggling with this issue for awhile in Unity. It seems that I cannot nail down getting smooth camera movement with player movement, specifically in fps. I got fed up of reading the docs trying to figure it out, and asked chatGPT, but it wasn't able to come up with a working solution for me.
what do you have right now and what about it isn't "smooth"?
So all movement is smooth, but as soon as I attempt to rotate the player/camera by moving the mouse, everything looks jank, and as if it's lagging behind
I think the camera is updating its position too many times in relation to the RB, and this is causing it to jump around
well... first off:
cameraObject.transform.position = playerObject.transform.position + new Vector3(0, headAdjustmentMeasurement, 0);```
Why manually move the camera at all?
Isn't it just a child of the player?
I'm pretty good at Java, javascript, HTML, CSS, but I'm new to C# as hindsight
Second - because you';re doing this:
playerObject.transform.Rotate(0, mouseX, 0); // Horizontal rotation on player.```
You are breaking your Rigidbody interpolation
so that will immediately lead to jitteriness
you should never touch the Transform of a Rigidbody directly
yes, I assumed I had to move the camera seperately from the RB in order to prevent x axis rotation of the RB
ah
no, if your camera is a child object, it's completely fine and you don't need to move it separately
To fix the Rigidbody interpolation issue you can replace that rotation code with:
rb.rotation *= Quaternion.Euler(0, mouseX, 0);```
You'll also want to double check that interpolation is enabled on your Rigidbody
I also usually use notepad++ and I find visual studio really annoying because it keeps formatting my code and doing stuff for me lol, know how to disable it?
Thankyou
I just dont want my entire playermodel to rotate on the x axis, is the only thing, that's why im doing it to the camera only
Yes that's not a problem - just make the camera a child
I have
VS can be configured to adapt to your own code style. But I wouldn't, as most of C# programmers use the "official" formatting conventions
Ill try your fix
It's just basic stuff like this: private void UpdateCameraPosition() { cameraObject.transform.position = playerObject.transform.position + new Vector3(0, headAdjustmentMeasurement, 0); }
I would write this to look cleaner imo like: private void UpdateCameraPosition(){ cameraObject.transform.position = playerObject.transform.position + new Vector3(0, headAdjustmentMeasurement, 0); } xD
you can change that
Just how I'm used to it in Java
KK, I'll find where to disable that
Yes this can be configured
lol nice
Settings > Text Editor > C# > Code Style
or something
Thankyou, I actually spent a lot of time searching for it before, and couldn't find it xD
What's the option that automatically fills words for you, sometimes I will have a Class name with a keyword in it, and it tries to fill my code with my classname instead, when I'm trying to use the keyword.
Intellisense
Intellisense code completion
As long as the name you type is cased roughly identically to the keyword, it'll prioritize the correct one
It seems to be broken for me xD
If you have a class Int { } and type "Int", it's going to prioritize Int over int because it's closer
Don't name types the same as keywords or common identifiers
I don't, but sometimes I will have a keyword in a class name like for example IncrementPlayerInt or something, and it'll just keep suggesting it lol
It also bases itself on usage, stuff you used before will appear more frequently. Not sure if there's a way to change that behavior
Should I apply this in FixedUpdate?
ah, I see, I just prefer barebones editors, it forces me to write well lol
Because I'm quite new to programming, I've only been studying it for about a year, year and a half
So the extra reps of typing helps me consolidate it
No, exactly where you have it now
Okay it helped a lot, but I think because of the lower frames of physics calculations, vs actual game framerate, the game looks lower fps now
Not sure how to fix that
Maybe if I interpolate the camera position update?
I'll just mess with this, and come back if I hit another brick wall lol
Wello, does anybody know how to call a function of a certain preset from another script?
What do you mean by "of a certain preset"
Well I have presets that spawn and I want to have it so when I click on one it gets selected
Do you have interpolation enabled on the Rigidbody
oh yeah my mistake
So, which one do you want to call the function on
I do
The one the code detects I clicked on, but most I can figure out is that it knows it's name
How are you detecting the click
Via an "Input Handler" which has the script and an input action (If that's what you mean by that)
Show !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.
I have a script to create a plane when a player clicks an object, and raycast from the camera to mouse position checking fo collisions on that plane
However, it's never registering collision
Can anyone take a look to see what might be the problem here?
using UnityEngine;
using UnityEngine.InputSystem;
public class InputHandler : MonoBehaviour
{
#region Variables
private Camera _mainCamera;
#endregion
private void Awake()
{
_mainCamera = Camera.main;
}
public void OnClick(InputAction.CallbackContext context)
{
if (!context.started) return;
var rayHit = Physics2D.GetRayIntersection(_mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue()));
if (!rayHit.collider) return;
Debug.Log(rayHit.collider.gameObject.name);
}
}```
So you want to call a function on rayHit. You have it right there
Get the component you want and call your function on it
sorry just got back, its not detetecting the enemy tag and playing the hurt anim
I'm gonna try it now
Anyone able to take a look at this?
Show your code again, also does the Debug.Log still not work?
just figured it out, but the particles arent displaying
Still, show code
SO i have this script here, i was following a tutorial and for some reason its wrong, can somewone help?
You have a function in your function
you also appear to be using variables that simply do not exist in the code
The correct way to use Debug.DrawRay here is Debug.DrawRay(ray.origin, ray.direction * 300, ...)
The ray that ScreenPointToRay gives is on the camera's near clipping plane, not (always) exactly on the camera
And the direction is not always the camera's forward, unless if it's an orthographic camera I guess
Have you confirmed that the raycast code is running?
Okay your issue stems from here:cs initialMousePosition = Input.mousePosition; // ... dragPlane = new Plane(targetObject.transform.up, initialMousePosition);
Input.mousePosition is in screen space but you are using it for a world space plane
update, i made 2 enemies but only one is displying [aticles
Is HitParticle a prefab or an object in the scene?
And what logs do you get when colliding with the enemy that doesn't display particles?
Including errors
oh, i was sure i was using the result from CastRay on that
https://gdl.space/rekupufowi.cs Okay, I interpolated my camera for smooth movement, and I can see it coming out of the player model, and the playermodel sortof glitching all over the place while moving, not sure why
First person? 3rd person? How is your hierarchy setup (camera, player, etc)?
First Person
Just getting the basics down, the movement is so jank, it looks like the player model bounces back and fourth
I don't see why you are lerping the camera position in UpdateCameraPosition
I don't need to, I know
(Not to mention that it's a https://unity.huh.how/lerp/wrong-lerp)
xD
I wanted the camera stable so I could sortof see what's going on
And now I can, and I see the playermodel glitching back and fourth really quickly when moving in one direction (the shadow)
Is there a reason to have the camera and playercamera objects separately?
Also a video of the issue would help
Ah, I just saw MainCamera and thought that's used here too
Btw this will break interpolation IIRC: ```cs
rb.rotation *= Quaternion.Euler(0, mouseX, 0); // Horizontal rotation on player.
rb.MoveRotation would respect interpolation
If you want to continuously rotate a rigidbody use MoveRotation instead, which takes interpolation into account.
eventually I'd like to make it multiplayer, so each player object is spawned in with their own cameras, I know I'm very new, but just for possibilities in the future
okay, thankyou
Try commenting out the whole rb.rotation = code for a moment, see if it still jitters when you walk
Hello. I am trying to use this script to control a character in 1st person 3d with player input. But for some reason no button works despite no error in the console. Player object looks like this.
kk
!code 👇
dang is the bot dead
It does not jitter haha
Bot is kill

Okay there we go, use MoveRotation instead then
Thankyou good sir
Although I'm not sure if you really need to rotate a capsule
It'll be replaced with a playermodel eventually
Yeah was about to say, you could just rotate the player graphics separately, have them as a child
In case the rb rotation doesn't work properly/smoothly
I was going to make a shooter, and I wanted hit boxes to be somewhat accurate
so I would want the objects to rotate
I think that's how you would do it?
I am trying to figure whether the problem is with the values in character controller or not
share your code correctly and maybe someone will take a look at it
#💻┃code-beginner message
You could make that work I guess
I personally ended up separating the rigidbody from the player completely lol. I just move the player object to the rigidbody manually
(FPS game)
This way I have full control over the rotations and they won't interfere with each other
Damn that's actually a really good idea xD, probably saves a tiny bit of performance not calculating physics rotations as well
just the playermodel rotation
It might be too large to send like that
I just checked and I do rotate the rigidbody, although I probably don't have to
not if you actually read the instructions
I'll keep at it, I'm attempting to make a game with similar core mechanics to Rust eventually
Is line 5 creating an instance of the ScoreManager class above it and just naming it instance?
Sorry. I missed the part in the instructions that let me send a code in message that transcends the text limitations?
Looking at rust, I'm like how the hell did they manage to do all of this
try actually reading the entire bot message
it isn't creating an instance there, it is a variable that will reference an instance of that object. you have to assign to it though
So do I share a link of it instead?
considering that is the only instruction for sharing large blocks of code, obviously yes
cool thank you :)
no, it's a declaration not an initialization
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Thanks for your help. Your condescending tone really motivates
next time try reading the instructions provided instead of skipping over literally the part that was relevant to you
dude, chill. just say rtfm and move on
I wasn't skipping. I was wondering how a C# file is harder to read on send file than on link
Are there any examples of large unity game projects out there? With access to the project. I'm curious how developers organize all of their scripts and assets, and also how they write scripts for different objects.
I see the entire code when I sent it here
Not everyone wants to download your file to view its contents.
But you don't need to download it to read it?
Oh my mistake. Point out where I can view the file without downloading it
yes, you do, the point being if you want help you make it easier for the helpers, not for yourself
I'm just sortof clueless when it comes to organizing a large project
My bad. I could see the entire code on my end
This server has guidelines for a reason, don't bitch when someone points them out to you.
It's not the guidelines that bothered me, it was the way you're talking
dude, why are you being condescending ot people in code-BEGINNER
not fucking code-expert
The most important thing to do when organizing your project is to do it in a way that makes sense to yourself since you will be the one working with it. Don't worry so much about how other people organize their stuff, do whatever makes the most sense to you
It's code-beginner not reading-beginner
No one's expecting people to be good at code but reading instructions should be pretty easy
i just don't think it's nice to be condenscending to people trying to learn something new is all
doesn't help anyone
The most important thing is to go with your first instinct, because when you need to find it later, that's where you're gonna think to look. "I think this should go in a folder named UI" becomes later "Where is this script? I'd probably put it in a folder named UI"
Used a link instead
Thankyou, I just find that I sometimes write a script, and realize that part of it should have been put on a seperate object, and I have to rewrite a lot. I guess that's probably just part of the learning experience
This is the way
Just don't be afraid to refactor as you, sometimes you don't have the full picture before you start
Good idea
Yep, refactoring your stuff when you realize you should do something a different way is what gives you the experience to do it the right way in the first place
Absolutely, that is why we design code structures before we start writing them
Good point
That's like, a second project or later problem. Gotta make the mistakes once before you know how to fix em
Do all devs do that? xD I've been learning about pseudo code in classes, but It always seems faster to me, to just start writing it haha
lol, false economy, you spend more time to refactor than you would designing first
If you lack the experience to design it beforehand then you just have to go with trial and error
Zero planning is actually better than poor planning
I see
If you don't know enough to do it right, you'll cause more damage than you'll fix
I was basically asking, so that I don't develop any bad design habits
To see if there's conventions of project organization to follow or something
take chances, make mistakes, and get messy. it's how you learn
How do you guys usually design your code structures before writing them? Do you write them out on paper, or like type up a pseudo code block example?
When am I allowed to repost my request?
Plan?
both
sometimes all of that, sometimes none of it. It's on a case-by-case basis.
learning when to do what comes down to experience
You give me far too much credit
so start doing!
I see 😂
I just winchester mansion scripts into being until I eventually finish the project or abandon it
Thankyou guys
||usually the latter||
sure, go for it
i just write it out on paint.net and just try it out to see if it works
if not then i go back to planning, or fix my trash code
Hello. I am trying to use this script to control a character in 1st person 3d with player input. But for some reason no button works despite no error in the console. Player object looks like this. And script is: https://hastebin.com/share/xujuzimaha.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
im curious what that would look like in paint haha
i got some pictures lol
dm me them, I wanna know all the strategies please lol
i made a thread
With this set to Send Messages, it will call functions of these given names, and there aren't any matching functions in your script
I usually just use paper or write stuff down in Google docs. If you have a good tool that let's you draw diagrams, then you might as well go along with that. Problem is drawing diagrams kinda sucks in most tools and it's hard to get the point across
That's a pretty neat way of doing it
paper or paint.net works wonders
im currently working on a A* pathfinding type thing
so i kinda have to do this
Is there any option to change that?
What do you want to do to read the input?
I was using a guide from 2022 which didn't include those functions on the send messages option.. I guess it changed since then
There's a lot of ways to interact with the new input system. Polling, events, messages, bindings
Bindings as in button pressed?
Pretty sure one of the other options in the PlayerInput component lets you bind a UnityEvent to each specific action
to choose which function it calls in the inspector
I don't remember what it is called
But it's something in that dropdown
I was only trying to create a player movement script with the new input system using a guide here: https://youtu.be/yWHqZoXJJ_E?si=XUUVYfHeE7fFjlqI
I have to admit that I am clueless as to what polling and events constitute
In this Unity tutorial we are switching our first person controller to the new input system
Follow me on twitter: https://twitter.com/passivestar_
Join our Discord: https://discord.gg/pPHQ5HQ
Events are the usual way to use the new input system. Polling is basically just what the old Input Manager does, and should probably be avoided
New input system has a suprisingly high bar. It's not easy to use if you're new to Unity...
I wanted to use it specifically to be able to use options like crouch or prone
you can achieve virtually anything with both systems, but I would suggest learning the new one as it's easier when you understand it.
Ik iv asked this before but i realy need to know how i can change nthis script so that when i collect all 25 start captuals, it changes scene.
What method would you recommend to be able to put those functions to use?
there are many ways of doing this.
I would suggets searching for a tutorial on Youtube.
Maybe something like "Unity, collect system".
actually I think CodeMonkey has a good one
watched it long ago
I have looked for tutorials but nothing works
i have to have it done in 30mins, how would i go aboutusing a list?
what doesnt work with the script you have now?
just check if Coin is higher than a threshold then change scene
im realy new to unity, how do i do that?
wouldnt it should be if 25 =25 then change the scene?? ohh btw put this code when coin gets collected
Is it possible to have a BaseMaterial, whose color is ffffff, and then apply this material on different rendered gameObjects, and be able to change each object's colors without having to clone the said material?
if(Coin >= Threshold){
//do something
}
put this in the if statement where u add the coins
its a float or int
so make a variable for it and change it in inspector
dude go on youtube and write "Unity collect tutorial"
There's like fifteen different ones on there.
oh, ok
if you do not know how to make a variable i suggest you !learn
my command pattern is making the player movement sluggish when there is a lot in the buffer from AI movement commands, is their an elegant solution to this?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ok
if you want to change the color on a single object then you will need to instantiate its material so it does not affect the other objects using the same material. getting its renderer.material will automatically instantiate the material. or you can do it manually using Object.Instantiate
(this information is assuming you want to do this at runtime, edit time requires separate material assets)
technically multi-threading.
I don't think that's where your issue is though, unless you've already optimized like crazy.
hmm does it mean public int/float = 1; ??
@devout flume This could be used too: https://docs.unity3d.com/ScriptReference/Renderer.SetPropertyBlock.html
[SerializedField] Private float/int Threshold; (you could do Public as well if you need this outside of a script)
Ok, well you answered my question about whether or not it is possible to do that within the editor. Thanks for your answer ! I find it quite difficult to achieve that, but I guess that makes sense since we can handle the shader part directly
ohh
Thank you, I will look into it 🙏
Though the doc of MaterialPropertyBlock says something about it not being too performant with SRP, but it's worth checking out
yeah i 
the current situation is extremely simple, just movement commands adding force to the player and two or three entities. noticable input jank compared to a situation that isnt using the command pattern.
Did you use the profiler yet?
It also sounds a bit like your movement depends on framerate
quake all over again
crushing statement.
It's usually an easy fix
My main project is to make a creation game in which you would be able to position elements around, change a lot of properties I define. Color is one of them. I developed the project in ROBLOX to realize that the platform kind of sucks, specifically when it comes to the physics engine, and I'm not even talking about the overall way the platform treats developers. Trying to see if Unity is a good choice but it's definitely not the same ideology behind 😅
Thank you for your help
use FixedUpdate if using RB or just in general
or deltatime for other movement method other than RB
depending on what you are doing ofc
fps is 200 - 400, the command itself is very simple ```public class MoveDirection : ICommand
{
Vector3 direction;
Entity entity;
public MoveDirection(Vector3 direction, Entity entity)
{
this.direction = direction;
this.entity = entity;
}
public void Execute()
{
entity.rigidbody2d.AddForce(direction);
}
}```
good u choosed unity ❤️
deltatime isnt framerate dependant afaik
Well you'd normally only use deltaTime (fixedDeltaTime) with MovePosition or rb.position, not with forces or velocity
Since addforce already uses deltatime by default
well ofc dont use deltatime with forces
let us know if u get stuck anywhere
im not saying use deltatime for forces, im saying use it other than RB movements so like Move() or something along those lines
Thanks a lot, I really appreciate it ! 
Is execute called only once?
dec_ves and osmal will help u 🙂
I cant promise that, as I am away sometimes
Yeah I won't promise I'm here for long, but probably again tomorrow
This is what the command invoker looks like: ```public class CommandInvoker : MonoBehaviour
{
private static Queue<ICommand> commandBuffer;
void Awake()
{
commandBuffer = new Queue<ICommand>();
}
void Update()
{
if (commandBuffer.Count > 0)
{
ICommand command = commandBuffer.Dequeue();
command.Execute();
}
}
public static void AddCommand(ICommand command)
{
commandBuffer.Enqueue(command);
}
}```
Yes for sure ! I ofc expect you to have lives, that's completely normal. You're kind enough to help people, that's already a huge thing
I believe that calling AddForce in the Update loop (as opposed to FixedUpdate) will introduce framerate dependency
the only time AddForce should be called in Update is when it is a one-off Impulse force
just look at quake for example and what framerate dependency does to games
It's a decent idea to keep your AI stuff in fixedupdate anyway, althought I've never seen anyone mention it except me
Or your own update loop but that's more complex
hmm. I do have the AI get the command through a fixed update: ```private void FixedUpdate()
{
foreach (var entity in entities)
{
//get cell where entity is at
Cell currentCell = flowField.GetCellFromWorldPosition(entity.transform.position);
//get move direction from flow field cell
Vector3 moveDirection = new Vector3(currentCell.bestDirection.direction.x, currentCell.bestDirection.direction.y, 0);
ICommand command = new MoveDirection(moveDirection * 1000f * Time.deltaTime, entity);
CommandInvoker.AddCommand(command);
}
}```
Yeah that doesn't help if you're executing it in Update
the thing is the movement works perfect when I apply the AddForce at the keypress
it just doesnt work as a command
Not directly related but worth mentioning that by default, AddForce will already be multiplied by fixedDeltaTime
So you have some redundant multiplications there
Do I need a seperate command invoker for player inputs? I dont want to do an anti-pattern with the commands.
Can't you execute the command from FixedUpdate instead?
Or if you need some commands to be executed in Update then you could have two different commandbuffers
Btw are you doing flowfield pathfinding or something? For an RTS?
I do have flowfield pathfinding in the project for now. its a roguelite that may have a lot of enemies / pathfinding projectiles etc
fwiw here is the input manager I screwed that up somehow: https://hatebin.com/vpjndqpsjn
Here's the problem, you are multiplying the direction with Time.deltaTime
That's fine in FixedUpdate, because deltaTime actually returns fixedDeltaTime, which is constant, when in FixedUpdate
But in Update it will change with your framerate
I must say I have never seen the command pattern used for continuous movement 🤔
delta time so far has never seemed to fix a single one of my issues
It seems almost useless
Usually good if you want to bring in multiplayer and rely on rollbacks/replays for network laggs/prediction mistakes
Okay that makes sense
I think just using the update functions correctly will eliminate the need for delta time. I also know nothing about this editor so far though lol
Definitely not useless, you should use it for any continuous change in Update/LateUpdate etc.
Can barely get smooth movement
Top 2 things you shouldn't use deltaTime with is mouse input and forces
What’s its use case even?
Like what does it do
Want to add 1 to a float over 1 second? Add Time.deltaTime to it in each Update
It lets you scale your values along with the framerate
Ah
If the frame took longer to finish then deltaTime will be greater
So it will account for that
That’s pretty cool, but isn’t the update function supposed to do that anyways?
It occurs every frame?
Nope, it just runs each frame
Ohh I see now
So it keeps track of calculations regardless of the frame rate
So if there’s massive frame drops, there’s no lag in calculations or logic that would’ve occurred
Lets say you add 0.1f to your float each update
If you have 10 fps then it will take 1 second to reach 1
If you have 100 fps then it will take 0.1 seconds
Ah
So it’s useful for server side logic, or anything where your client has to keep track of things over realtime basically
Man there’s so much I don’t know about these engines xD
Not sure about that. Pretty sure that server side logic happens at fixed intervals
But I'm no networking expert
I agree, server logic usually is in steps passing in timestamps to compare against
stop crossposting #📖┃code-of-conduct
I removed the delta time code, no effect. Either way it works perfectly until the command pattern is introduced.
Thread
Forgot to mention that you should probably do HandleInputs in FixedUpdate too, so you don't get multiple move commands for one physics frame
But your issue might be something else
planning to make a 2D story game with a general map, and buildings to enter in etc
is it recommended i use scenes to travel between these events or should I just manage what in game event is going on based on code and have the master scene control everything?
both work and its mainly preference / requirement of your project
im trying to learn unity, Im having a hard time finding good ways to learn though because on youtube it shows how to write the code but its difficult to not just copy it and find a way to test yourself, does anyone know of any rescources on how I can actually learn instead of just copying
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Set yourself a goal (a game you want to make), try to get there by reading the documentation. Pretend YouTube doesn’t exist. Read books on the principles of making games.
@languid spire thank you but is there any others? I have tried that before but I dont love it, due to the website
Hey, I'm planning to change the serialization method of data in one of my data types. The data type is used in several prefabs, and I want to maintain the data in the changing format. Is there any straightforward way to do this?
@ripe shard thank you
The key is to figure out how to figure stuff out nobody has figured out yet
This allows you to intercept serialization calls https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
Wdym by format
Hello, I'm using the code below on an enemy in a game I'm making so that it will walk to random points forever until it spots the player, but I was wondering if anyone had any ideas for making this a bit more realistic. It doesn't need to be anything crazy but right now there are many instances where it will just keep walking back and forth and I want it's path to be a bit more realistic than that
{
Vector3 randomPoint = center + Random.insideUnitSphere * range;
NavMeshHit hit;
if (NavMesh.SamplePosition(randomPoint, out hit, targetDistance, NavMesh.AllAreas))
{
result = hit.position;
return true;
}
result = Vector3.zero;
return false;
}
void Patrol()
{
if (agent.remainingDistance <= agent.stoppingDistance)
{
moveRange = Random.Range(2, 5);
if (RandomPoint(transform.position, moveRange, out point))
{
targetPos = point;
agent.SetDestination(point);
Debug.DrawRay(point, Vector3.up, Color.blue, 1.0f);
}
}
}```
define "realistic"
you mean you wait before you go to another point?
do you want the enemy movement slower when patrolling?
give details
well realistic was a poor choice of words
give your enemy some random times to pause and do something else instead of just hitting each point like a clock
Make it go grab a coffee every now and a while to make it more realistic.
one my enemy reaches a patrol point it usually looks around, picks a random look at target and IK turns its body or does something before going onto next point
I would pick a few points and score them, give smaller score to points that are in the same direction as the previous point(s)
I did that just recently
i am in the making of a custom navigating enemy and what i do is it just to stay still for 5 seconds
then to go to another point
since the point where it will walk appears at a random point within a certain radius from the npc, sometimes those points will appear directly behind it and it'll do a full 180 and walk towards it, and then do it again so its just walking back and forth. so I mainly just want points to not appear directly behind it that much
Pauses do sell it quite well, but turning around constantly can still look a bit odd
use dot product and only add a point if its within threshold front/fov where you're not doing a full 180
Make your point generation algorithm more sophisticated
Yeah my suggestion would not let that happen - or at least not that frequently
you could just make it so it cannot pick the previous point twice
i mean you could also increase resolution of points so it practically cannot create the same point twice 🤷♂️
issue isn't repeating points but them generating behind player
yeah since they're random and the enemy keeps moving it's already extremely rare it'll hit the same point twice
Theres a very small chance that it would pick the same point, its using insideUnitSphere
thats what increasing the resolution tries to eliminate or does it just make behind points no matter what?
Hence the suggested angle/dot product check
which resolution ?
wdym which resolution
you said "resolution of points"
Yeah it's not on a grid, the resolution is "infinite" or as large as floating points allow
yeah, changing the resolution of them AKA creating more or less in a specific range
alright
on your second point, that's what dot product would do
limit which ones would get added as possible
I use a custom A* for this that has a higher "cost" for points you recently visited
that seems like it would work
indeed. done it before, I'm sure it works
a while loop and enough of a high number for "maxTries" just incase something goes wrong :p
how would i go about implimenting that?
generate a point, check the dot if its within range add it to the possible points. If not keep iterating
Yeah compare the dot product of (playerPos - lastPos).normalized and (playerPos - randomPos).normalized
If it's too high (say, over 0.5) then generate another point
sorry poor drawing skills lmao
You can also use Vector3.Angle instead of Vector3.Dot if that's more clear to you
thank you, i will try some of these out
you see the blue is the number on the right, the dot product cs float dot; Vector3 dir; private void Update() { if (target == null) return; dir = (target.position - transform.position).normalized; var forward = transform.forward; dot = Vector3.Dot(forward, dir); }
closer to 1 = infront / closer to 0 = sides and anything below 0 is behind
replace the target.position for the generated point and do the rest based on dot or angle
what is on the right side of your screen ❓
in the gameview?
playing around w shaders
thats some cool color banding
the gif is gonna look more shit due to compression, trying to add headcrab types lol
circle pixels
https://paste.ofcode.org/xqMYUzB64ccpzL5kQMQigy
how do i make it wait till the animation is done ?
did you debug IsAnimationFinished
ive ask gpt for that function so i have no idea how AnimatorStateInfo works
it tells you info about the current state lol
im using changeAnimationState mostly
aka animation clip inside the animator
to play the animation
also probably better to learn this stuff instead of gpt
this part looks sus && stateInfo.normalizedTime >= 1.0f;
I knew that looked like AI code
well maybe it works but I only needed to check the name in update, I suppose that gives extra check
my AImeter was ticking
the idea is somewhat correct, the execution is mid
yes but you have no idea what this is doing ?
yield return new WaitUntil(() => IsAnimationFinished(_PLAYER_ATTACK3));
you would have to check if those are even hitting / waiting
combination of checking animator and prob putting it into a bool you can debug
id like to do it but animation is like hell
nothing to do with animations, Im talking about code
yea working with the code animation is so confusing
also possiblity to just use animators built in exit states from FSM
or Animation Events
well if you dont understand it, it is
if you do, then it wont
I think Unity has a good GUI for animations where you don't have to bother with the coding, if you really don't want to learn it. A lot of videos online
can someone help me, i cant get the unity 2d grid to show and nobody knows why it isnt showing
sry wrong channel didnt realize
Hitting on a (you got it) bit of snafu
I have a script that creates a virtual plane, and i should be able to drag an object along that plane
I want it to only be able to be dragged in one axis, so, in all of my wisdom, implemented Vector3.Project
However.
!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.
This is the script running on that
Thing is, if at line 54 i replace "Vector3.Project(hitPoint, transform.up);" with just hitPoint, it drags fine, just not on that axis
So, what am i not getting about the Vector3 Project?
Probably the fact that projecting a world space position on a direction vector doesn't really make sense in this context
You could transform that point into the object local space, project it on the direction vector, then inverse transform it back into world space.
Or just assign it to transform.localPosition instead of the last step
Though, you might need the direction vector to be in local space as well🤔
Don't have much time to think about it.
You should do some math/ sketching on paper before actually writing the code.
Yeah
I'm trying to look into TransformPoint but no luck there
I'll try editing that tomorrow
is mouse delta supposed to stop working when the mouse winds up at the edge of the screen?
just read the documentation for the pointer class, guess so.
how do i make a two dimensional array with x rows and y columns?
private int[,] layout = new int[x,y];
This doesn't seem to be working...
Doesn't work in what way?
It's only making two rows, but the number of columns is right
How are you confirming that?
uh oh
maybe my printing code is wrong
private void PrintGrid()
{
string line = "[";
for (int i = 0; i < rooms*2; i++)
{
//print("i" + i);
line += "" + i + ":[";
for (int j = 0; j < rooms * 2; j++)
{
//print("j" + j);
line += layout[i, j] + ",";
}
line += "]\n";
}
line += "]";
Debug.Log(line);
}
trying to print the whole array into the debug console, only two lines show up
dog
can i be so real
the editor only shows two lines
after i clicked on it you can see all the lines
i've been on this for 15 minutes
thank you
😭
Good opportunity to discover that error and info messages have more info than you can see in the list.
🤦♂️ today is the first time i've used the VS 'Code Cleanup' button. would not have minded utilizing it earlier
I'm constantly hitting the reformat button in Rider
Thanks
!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.
{
if (lastTemperature1 != null && lastTemperature2 != null)
{
// Check if lastTemperature1 is colder than lastTemperature2
if (lastTemperature1 > lastTemperature2)
{
// Change the LineRenderer's material to reflect cold temperature
lineRenderer.material = coldMaterial;
}
else
{
// Change the LineRenderer's material to reflect warm temperature
lineRenderer.material = warmMaterial;
}
}
else
{
// If no temperature data is available, use the default material
lineRenderer.material = defaultMaterial;
}
}```
Is this right way to change line renderer material in run time?
Does it not work?
#💻┃code-beginner message Oh, i love the Format Document option and use it regularly. 🙂 differently, this particular Code Cleanup button follows preset, definable rules, and in this case just removed the unused usings at the top. it can do much more, but that was all this particular file needed
3rd?
I have 3 material to choose from
I have assigned them respectively and it always shows the index 2 material
Where does it show it? Does your code actually run?
It is running
Taking inputs
What inputs? I don't see any inputs in that code? How do you know that the shared code is running?
Can I share my log
Sure. Follow the !code sharing guides
📃 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.
UnityEngine.Debug:Log (object)
BallController:UpdateMaterialBasedOnTemperature () (at Assets/hehe/BallController.cs:129)
BallController:TracePath () (at Assets/hehe/BallController.cs:119)
BallController:FixedUpdate () (at Assets/hehe/BallController.cs:52)
Drawing with warm material.
UnityEngine.Debug:Log (object)
BallController:UpdateMaterialBasedOnTemperature () (at Assets/hehe/BallController.cs:145)
BallController:TracePath () (at Assets/hehe/BallController.cs:119)
BallController:FixedUpdate () (at Assets/hehe/BallController.cs:52)
Collided with ice cube. Temperature: 99
UnityEngine.Debug:Log (object)
BallController:OnCollisionEnter (UnityEngine.Collision) (at Assets/hehe/BallController.cs:63)
UnityEngine.Physics:OnSceneContact (UnityEngine.PhysicsScene,intptr,int)
Both temperatures already assigned.
UnityEngine.Debug:Log (object)
BallController:OnCollisionEnter (UnityEngine.Collision) (at Assets/hehe/BallController.cs:82)
UnityEngine.Physics:OnSceneContact (UnityEngine.PhysicsScene,intptr,int)```
It says drawing with warm material
I think I did something stupid somewhere along the environment
Where is that log printed from? I don't see it in your shared code.@cloud oak
Hey can someone help me with my code? its not working for some reason.. (its my first day)
I can screen share it
but i asked someone else who doesnt use unity and he said it looks like the code doesnt exist
so if anyone wants to hop on call and help me that would be appriciated :D
a recap of what was said in the General room
my project got corrupted, whole scene is gone but the code is still there. any help to recover?
Don't open the project, if you do there is no path to recovering the scene
wdym?
wdym, wdym? i really cannot say that any more clearly. perhaps read it again
Oh, sorry i just didnt understand why you had to say that, thats all
You'll need to explain the issue better and provide the relevant code.
oh
mostly so i don't get yelled at for sending you here 😁
So that people here would know the context.
!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.
wait how do i sent it in the black background
follow the bot message
If you didn't reopen the project your scene may be in Temp/__Backupscenes. Add it to your project, renaming its extension to .unity and it may be able to be recovered.
If you did open the project that folder is cleared out.
Also for next time, this is a coding channel, the question is more suited to #💻┃unity-talk
ok tysm!! <3
hello, just fixed my scene and now have another issue lol
Wouldn't using revision control help with such issues like missing scene?
my animation isnt speeding up and i have tried speeding it up in animator and actually making the frames closer together. any help?
At least that you (unlike me) don't forget about checkin changes after youre done lmao
Using the line renderer i have drawn Lines. The line renderer is on a UI Object in the Canvas and i want the lines to either follow the camera or the object its attached to but if i turn off world space the lines will no longer render.
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private RigidBodt2D rb2D;
private float moveSpeed;
private float jumpForce;
private bool isJumping;
private float moveHorizontal;
private float moveVertical;
// Start is called before the first frame update
void Start()
{
rb2D = gameObject.GetComponents<Rigidbodt2D>();
moveSpeed = 3f;
jumpForce = 60f;
isJumping = false;
}
// Update is called once per frame
void Update()
{
moveHorizontal = Input.GetAxisRaw("Horizontal");
moveVertical = Input.GetAxisRaw("Vertical");
}
void FixedUpdate()
{
if(moveHorizontal > 0.1f || moveHorizontal < -0.1f)
{
rb2D.AddForce(new Vector2(moveHorizontal * moveSpeed, 0f), ForceMode2D.Impulse);
}
}
}`
Rigidbody2D not Rigidbodt2D
oh wow.. just a simple typo..
if your ide did not highlight this you need to configure it
these scripts can't be found, if you're not using whatever was here any more you should remove them
I fixed that but its still not working for some reason. Do you think i maybe set up my VS wrong?
If you're not seeing errors underlined in red and autocomplete then you need to configure it
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
Warnings and errors in Unity are generally unrelated to IDE setup
To specify the type for generic method you need to place it <here>(before regular parameters)
hell no i js noticed i put () instead of <> 💀
do I just follow docs or there better source for learning like in youtube?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ty
Docs and manual are always good though
I'd suggest to use docs once you understand basic concepts.
Use tutorials to properly get started first.
🫡
um i need help
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UIElements;
public class Tile : MonoBehaviour
{
List<GameObject> hitCollider;
int x=0;
// Start is called before the first frame update
void Start()
{
hitCollider= new List<GameObject>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if(this.name=="Tile")
{
//x++;
//Debug.Log(""+other.name);
hitCollider.Add(other.gameObject);
/*if(x==4)
{
foreach(string c in hitCollider)
{
//Debug.Log(""+c);
}
}*/
}
}
public GameObject[] Collisioni()
{
return hitCollider.ToArray();
}
}
PlayerManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerManager : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
GameObject[] collisioni=other.gameObject.GetComponent<Tile>().Collisioni();
foreach(GameObject col in collisioni)
{
Debug.Log(""+col.name);
}
}
}
Guys am having a strange issue with my code, basically my PlayerManager code calls the function Collisioni() from Tile.cs when it touces the tile and should return an array containing the object that that object is touching, but it only returns half of what is touching. I already tried debugging and the results are:
if i try to print the elements of the list at the end of OnTriggerEnter of Tile.cs it gives all the collisions ( is 4 object in this case), but when i print on Collisioni in Tile.cs it only gives me 2 of them.
whenever i try to make a new script it cant open, and im pretty sure its because unity cant find my visual c++
Do you have compiler errors or somethign in editor?
no it just says "check external application preferences"
and when i got to preferences i see the thing to change it to visual c++ but visual c++ isnt an option
the only option is "open by file extension"
You might be ahead of time with checking the list, as the physics system did not query all collisions yet, but you are already trying to access them
i thought of that and i tried to do a while statement in the Collisioni function while(hitCollider.count<2){ Debug.Log("waiting") }
but it just gives an infinite loop
should i just delete unity and visual c++ and just reinstall? i feel like there has to be a better way to fix this
Why dont you just check if the player hits the tile, then call a function on the player to pass in your tiles collisions
I am wondering, where the c++ thing is coming from, but I am on mac, so not sure what its supposed to be called on windows
Did you install it with unity hub along with a unity version?
isnt it what am doing? passing the collisions of the tile through Collisioni() ??
yes but then i tried to delete and reinstall it because i was having some issues and now unity doesnt open visual c++
oooh you mean that
i did that before and gives the same issue i switched up to gameobject to see if it was a problem of collisions
Physics system is firing both ontriggerenter at no specific order, so you dont know, when the actual collision gets added. The tile should call the player, not the player ask the tile on its own collision detection. Lets say, player hits tile (collision 0 happens) and gets the collions of the tile, its 1, but then the tile progresses its own ontrigger check and adds to the list, but the list has already been fetched by your player.
Not sure its clear. The player got the current list before your tile was able to add and check its own collisions. shorter version 😄
Also, the List is only created once and added to, so the count will increase with each Trigger
yeah but by adding a while statement inside Collisioni() in Tile.cs shouldnt it wait until for example hitCollider.Count > 2 so for atleast this case should give me all 4 collision
but it just gives an infinite loop
how did you make it wait until?
like this for example
in this case the collision are 4 so it shouldnt give an infinite loop
i did this and it shows me that it prints the results before it could even insert the collisions in the list
so the issue is that
the first 2 logs in the console are the Debug.Logs of Player.Manager
is there a way to make the playerManager wait or should i approach it in an other way
@astral falcon I ended up fixing it somehow thank the lord
i just started unity literally yesterday and everything is so overwhelming
Well, I told you what you could do to get the latest correct array
how do you make your code different colors
in VS code?
yeah
use c# and unity and unity snippets extension
!vscode
☝️ setup instructions
ty
You need to get the latest collisions at the time of your tile check. You could wait a frame but that also could mess up things because the collision list could have been updated already
what if i use a boolean in Player where it only call the function Collisioni when its true , and the bool its true only once all the collision of Tile are stored in the list?
but at this point i should use OnCollisionStay instead of OnTriggerEnter
it works now like this @astral falcon thanks for help ❤️
just asking but how do i know if an object registred all collisions, cause in this case i said if ontriggerenter has been executed 4 times its all of them but if the collision are 3 or even 5 what do i do
whats the condition
I'm getting stuck with vectors.
I have a vector which is (moveInput.x,0,moveInput.y).
I'm trying to rotate this vector based on which way the freelook camera is looking, ignoring the y direction.
I tried to do
Vector3 output = Quaternion.AngleAxis(Vector3.Angle(Vector3.forward, new Vector3(mainCam.transform.forward.x, 0, mainCam.transform.forward.z)), Vector3.up) * new Vector3(moveInput.x, 0, moveInput.y);
``` but this doesn't work and starts to mix up controls when the camera is rotated.
I think Vector3.Angle is messing with me but I have no clue how to fix it. anyone know?
why cant i add my InvSys class?
Show us the inventory system script
The file name looks correct but if the class isn't the correct type, you'll not be able to drag the file to the inspector field.
you are dragging the script. You need to drag an instance of the script
any idea why this is happening?
the rules do work, but it spawns the whole palette infinitely
Vector3 camForward = mainCam.transform.forward;
Vector3 flatForward = Vector3.ProjectOnPlane(camForward, Vector3.up);
Quaternion rot = Quaternion.LookRotation(flatForward, Vector3.up);
Vector3 output = rot * moveInput;```
This is what I would do^
I'm not sure I understand the ProjectOnPlane and LookRotation
Hello folk
My question is about platform jump. When player jump through a platform, it jumps normal but when the player tries to jump through edges of the platform, the player jumps less than normal. I am gonna share the script and an image to clarify it better. Thank you in advance.
{
public float jumpForce;
public float jumpSpeed;
private Rigidbody2D _playerRb;
private bool _isGrounded = false;
private void Start()
{
_playerRb = FindObjectOfType<Rigidbody2D>();
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Player") && !_isGrounded)
{
if (_playerRb.velocity.y <= 0)
{
_playerRb.AddForce(Vector2.up * jumpForce, ForceMode2D.Force);
_isGrounded = true;
foreach (ContactPoint2D contact in other.contacts)
{
if (contact.normal.y <= 0.5f)
{
if (_isGrounded)
{
_playerRb.AddForceAtPosition(jumpSpeed * Vector2.up, _playerRb.transform.position, ForceMode2D.Impulse);
if (this.gameObject.layer == 6)
{
if (TryGetComponent<DestroyBreakFromTop>(out var _destroyBreak))
_destroyBreak.DestroyBreakPLatform();
}
_isGrounded = false;
}
}
break;
}
}
}
}
}```
ProjectOnPlane is vector projection to get a "flat" camera vector (no up or down)
LookRotaiton is just producing a rotation based on the look vector
What kind of collider is your player using
Both my player and platforms have Box Collider 2D
foreach (ContactPoint2D contact in other.contacts)
{
if (contact.normal.y <= 0.5f)
{
if (_isGrounded)
{
_playerRb.AddForceAtPosition(jumpSpeed * Vector2.up, _playerRb.transform.position, ForceMode2D.Impulse);```
you're adding additional force for each contact in the collision
the scenario where you're hanging half off the platform has fewer contacts
so less force is being applied
You can do Debug.Log($"Contact count: {other.contactCount}"); to check
There's also a couple of if statements in there
so even if the contact count is the same, sometimes not all the contacts will have a force based on this code
Also the foreach will only ever run once
Oh yeah true - that's wild
it should really just be:
var contact = other.GetContact(0);
// do stuff with it
And get rid of the loop entirely
so really what's happening is that the first contact in some of these is satisfying the condition, and in others it is not
it says 2 whether i jump in the middle of a platform or from the edge of a platform
ok i am trying
I walked through it all with documentation and I understand it now. thanks a lot 
count the number of times force is added
that would be more accurate
awesome!
Does it work?
yep
cool
now I can also define up based on a normal vector or the inversed gravity direction to support other surfaces
absolutely!
This script is attached to every platform i have. I am spawning platforms based on player's position. Even with this scenario, that for loop will run only once?
ok i ll try that one if i find hwo to count it
with an int
i found it
int times = 0;
Then every time you add force
times += 1;```
then log it at the end
or just print each time it adds force and count the logs
you have a break at the end of the loop so it will only do one iteration per platform
the first one is force count and the second one is contact count (which is always 2). I waited for a while to let my player jump and this is the max jump height when the player jumps on the edge.
hello guys i was following tutorial od 2d tilebased rpg and i have 2 problems with my code if someone is free to help.First is my SpriteRenderer doesnt change my weapon sprite and second is my enemy doesnt follow player for some reason but it goes to starting position.
yeah that's right. I overlooked it
Focus on one problema at a time and share details/screenshots/code
I'm encountering a strange bug where a TextAsset is not null but when accessed, is null.
Debug.Log(interaction is null); // false -> The base object
Debug.Log(interaction?.Dialogue is null); // false -> The TextAsset
Debug.Log(interaction?.Dialogue.text is null); // NullPointerException because Dialogue is accessed, but is null
How is that even possible
Alirght so i was following this tutorial https://youtu.be/b8YUfee_pzc?si=ueajmC6Q1P0opadU&t=19275 and weapon changes in game manager and as u can see down on pictures it updates.But physical object in game doesnt.
2024 edit!
I've got a new course teaching multiplayer here on youtube! Check it out
https://www.youtube.com/playlist?list=PLmcbjnHce7Scovukpm2UbvBmhPKvM52uD
--- Livestream alert ----
I'm live every Saturday morning, come say hello
https://www.twitch.tv/n3rkmind
This is a full release of an Top Down RPG course made in Unity 2017
Here's a link ...
For further reference, this is how the object looks like in the inspector
Is None maybe not the same as null?
so Dialog is obviously null there
is null can't be used with Unity objects
use == null
Ohhh
Same with the ?. operator