#💻┃code-beginner
1 messages · Page 429 of 1
properties for ya
soo even if u could manipulate it.. it'd do nothing for ya
structs
yeah because its value type
words 😈
lmao
i love lamp
wait let me remove it before i get muted
damn , is there any workaround for that
you'll get mutated
thers a different timescale u can change if i remmeber correctly @cinder crag
navarone would know
computerman
unscaledTime
wassthat?
its only readonly
oh Timescale ? It would not affect Inputs unless you're doing * time.deltaTime
im still looking.. i havent had this issue yet.. but im sure i wil
soo might as well learn w/ ya
yes assigning value to unscaledTime makes not much sense, its like trying to assign time.deltaTime
smth like this?
what are you even doing here lol
shop , when im the shop area and press E , it opens and when i let go of E , it closes the shop
https://discussions.unity.com/t/get-input-while-time-timescale-0/70861/2
https://forum.unity.com/threads/getting-input-when-time-timescale-0.195703/
https://www.reddit.com/r/Unity3D/comments/12pzqoo/why_arent_my_buttons_working_when_timetimescale_0/
https://www.youtube.com/watch?v=KPaEnLpu57s
@cinder crag some fast resources i found
why are you multiplying time.deltaTime for timescale
theyre not using new input system
timescale would not affect inputs, but it does affect physics loop
maybe using the new input system could be a solution
maaannn
iono ¯_(ツ)_/¯
putting inputs inside triggerstay is likely a big issue
use a bool you detect in Update for inputs
if this is true.. then his issue is not what he believes it is
ahh physics
yeah they probably have something else wrong
yup yup
i have to re-do my pause system.. b/c it uses timescale.. i dont believe i wish to use that
mainly physics and animations are 100% affected by timescale (that includes fixedupdate etc.)
I use a static Event
ya i mentioned this earlier.. #💻┃code-beginner message big spoonfed dump
if something in script cares about "pausing" it will do so
sounds gucci
unity event or delegate?
okay fixed evetrything
can either be automatically triggered (onenable) or.. manually called
look at you "levelling up"
the problem was i wasnt puasing the game when in the shop so when i press to buy the pistol , it charges the bow then destroys it and adds the pistol fast so thats why it would be stuck with the bow dmg
so now that im pausing my game it works epicly
awesome! glad u trouble-shot and figured out what the real issues were
my player still jumps around while navigating my Pause menu 🫣
lmao
im glad it doesn't just <crash> lol
my problem is the exact opposite.. (when i built my pause menu) i was under the assumption that everything would pause..
MouseClicks do not count
my player doesn't move around (b/c of physics) soo i thought if he didnt move he couldnt shoot.. thats not how it works
im gonna yoink this for my system if u dont mind 🙂
https://gdl.space/vujisecopu.cpp i jsut did this and it works fine lol
doooitt
even made it soif u press E again , it closes it
fixed the problem i had since last night , man that feels good

doesn't it?
if you think coding is painful, wait until you actually start programming
it gets easier.. thats when u gotta step ur game and make it painful again
(thats when ur learning)
Spawn camps u used a character controller right?
How did you fix the camera when crouching so it changes eye heights
with the crouching
trueer
Move the camera target down
you could just scale your parent object so the camera target scales with it
thats what i do
What do you mean with camera target?
Can you explain painfully detailed cause i dont understand
im still really new to unity
im 4 days in
is your camera in your character or in an empty?
In my character
You're still using a base unity camera aren't you
it didnt get fixed , the pistol dmg is now 0 , the buy happens when i shot and enemy with the bow doesnt matter what dmg i deal then go to the shop , buy the pistol and the dmg is still 0
Not the one thats provided when creating the project
You should be using a cinemachine camera if you want anything more complex than a static camera
Let me check what im using
so scale your parent object down and it should move your camera down, although janky. otherwise you could make another script that makes that camera object snap to another object i this case an empty called camtarget. and it will scale the camtarget instead of the camera
easier
and you do not need cinemachine to make good camera movements, you can code them too.
worse way to do it scaling the player entirely
the camera target / offset is the best way
every way is different
head be hurting
it does that
yes but not every way is good 🙂
scaling the player down is an alright way to do it as long as you are not scaling camera.
Well atm the target is the character controller itself and its offset with 0.65 lu
yeah u do that, its gonna create worse problems lol
i do, i have no problems
also what does it mean when someones code isnt "safe"
my friend said that to my code
Depends on the context
Ask him what he meant. Could mean a ton of things in the context of a beginner
It could mean prone to errors, it could mean vulnerable to attacks
it could mean literally using the C# keyword unsafe
He could feel very threatened by your code
He said that to the way i used enums
What is "The way you used enums"
nsa watching their code
having a problem i want my cube to stop when it hits the obstacles and i got it to work but it only works for 3 when i add a new obstacle and i run into it with my cube it will keep going idk why
how do you figure we know whats wrong from these screenshots alone?
I too feel threatened by this
Are they on the same collision layer? Do they have collision boxes?
The fact that you're casting them to int to store in MovementState means that MovementState is just an int. Meaning it can hold any int, not just values the enums represent, which can lead to errors. Why isn't MovementState of type MovementStates?
well i was wiating for someoen tp respond so i can go more in depth
Also this
thats a waste of time. Next time clearly state the issue and show the appropriate inspectors and code
ahh makes sense
well it works and i dont use the variable yet so im perfectly fine with how it is atm
collision layer?
You should change the type to MovementStates instead of int
It'll also be significantly easier to work with
collision layerZ?
In your inspector window top left you can see what collision layer they are on. Its always on default in the beginning but for safety change them all to the same collision layer
anyone know how to fix this?
idk what that means im afraid
Change the type of the variable
to the enum type you've made
ohh now i get it
The entire point of an enum is to be a type you can store in a variable
is it beside layout?
The only course i took which was 4 hours before diving in the deep end kind off skipped past it a little bit
dw its a part of the process
what layer do i put it on
Which ever you want aslong as they are on the same one
are you following a brackeys tutorial?
yeah lol
haha knew it
what software you use to create yours sprites? (Pixel Art)
yeah cause default hits all of them but im teaching you a good habit to have so they only hit what they are meant to hit
Probably a question for #🖼️┃2d-tools or #🔀┃art-asset-workflow
pixilart
is solid
its a website
but works well
the problem is that when i collide with the three obstadcles i have rn there fine i wrote it to when it hits an obstacle it stops but some obstacles dont work and my cube just continues on its way
ok
are the collision boxes checked?
in the inspector you see the mesh and collision box
yeah
collision box needs to be checked for collisions to work
it is
How fast are you throwing the box
wdym
If its unreasonably fast it could go thru the thing without a frame being loaded in to see what actually happened
that is pretty odd idk what it might be
Show the inspector of an obstacle that "doesn't work" and if possible one that does
oh wait
when it hits, my playermovement doesnt turn off
off
only foes for the three i have on right now
weird
What is supposed to be turning off and what makes it do so
What is the "it" that turns off collision and how does "it" do that
do u recomend another one to dowload?
MSPaint
Does this mean that im trying to access a deleted object?
NullReferenceException: SerializedObject of SerializedProperty has been Disposed.
okay when my cube collides withb the obstacle the obstacles are coded to turn off my playermovemtn when impacted with my cube
Check the stack trace, it'll tell you what functions called what to get to that error. If none of it is in a script you wrote, you can probably ignore it
Okay what is that code
it works for 3 obstacles but the rest dont work
!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.
How do i check the stack trace?
Click on the error
it'll be in the bottom of the console window
Just follow the breadcrumbs and look for a script you wrote. It's an editor-only bug, so unless it's from something you wrote you can just ignore it
it won't affect a build
Ok, thanks
Okay, is this script on the player or on the things you're colliding with
Okay, and what are the names of the objects that aren't working?
obstacles
3 work but when i add more thye dont do what i want them to do
weird ot me
Show a screenshot of the inspector of one of the ones that doesn't work
you have literally cropped out the most important part of this object
yeah mb
Okay, and this is one of the ones that is not working?
Make sure the object is named Obstacle and not Obstacle or something
||or better yet don't make the name relevant in code and check something else||
usally when i add a 3rd one
Then add a 3rd one and show me that
wdym
Direct your attention to your own function:
#💻┃code-beginner message
What does this line of code do
if collided with what
obastacle
Just the one line I linked
obstacle
Okay, and tell me
Is this object named "Obstacle"
,mmmmmmmmmmm last time i even changed ot obstacle it didnt work lemme check again
loll
Code does exactly what you tell it to
If you code in "Check if the object I hit is named Obstacle" then that is exactly what it does
Obstacle (1) is not Obstacle.
yeah still doiesnt work
There's no such thing as "close enough"
hi.
Show a screenshot of your entire Unity window with:
- The scene view showing the player intersecting with this obstacle
- The obstacle selected and its inspector visible
- The console window open and visible
Should put this in a thread as well. @round plover
Yes, when you have the screenshot open it in a thread
okay gonna be hard screenshoting it as soon as it hits the obstacle but okok
You can pause playback
@round plover Thread
as for the other three fine i moved them aside
Best not to ignore the mods...
i have this line to acces the playerscript: public Playerscript script;
but for some reason i cant drag the playerscript inside of unity
make sure you are dragging an instance of the component and not the script file itself
Are both objects in the scene
no
Then you cannot drag one into the other
I'm assuming one of them is a prefab
you cannot drag a scene object reference into a prefab
digiholic how to i dup without it becoming Obstacle(1)
each time
i want it to just stay as Obstacle
good lord , i deleted the chargeable bow code and the pistol dmg is literally being copied from the bow dmg for some reason and i dont know how to fix it at all
I literally answered this in the thread
@round plover Why are you posting outside of the thread again?
i didnt'
any idea why?
You need to debug that to get an idea
track down the origin of values
See the debugging guide in the pinned messages
im already debgging and i literally dont know where the problem comes from
Then post your attempts here, someone will guide you how to do it properly.
we would need to see pistol damage script and bow script to find this issue
theres no bow script or pistol damage script , its jsut one script that handles all of that
lets see it
theres not a single line of code that sets the weapon dmg to the bows dmg , i looked in every goddamn script and i cant find one line of code that does that
what is the WeaponStats script and can we see it?
Don't forget to show how you are debugging it as well
scroll down in the script i sent
lets see the WeaponsSO script, im having a hard time believing you are not setting damage in any script
its just a SO
wait hold on
I FIXED IT
OH MY GOD
I FIXED IT

Trying to create a 3D game that operates like a 2D game (much like overcooked! and plateup!
the way my character moves right now is fine, however when I stop moving the character automatically rotates back to facing north.
how can I make it keep it's current rotation when the player stops their input?
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public float speed;
private Vector2 move;
public void OnMove(InputAction.CallbackContext context)
{
move = context.ReadValue<Vector2>();
}
void Update()
{
movePlayer();
}
public void movePlayer()
{
Vector3 movement = new Vector3(move.x, 0f, move.y);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement), 0.05f);
transform.Translate(movement * speed * Time.deltaTime, Space.World);
}
}
hey- im somebody from godot trying out unity
how would i, in an if statement, do or
like
if (blah=true or blah=false)
ok, thanks!
Also ==
The reason(or at least one of) is you using slerp incorrectly. Check the documentation and see what the third parameter is supposed to be.
i wanna show my game here like 1 vid of it , but idk if i can
the 3rd param is the speed in which the player rotates right?
No. Did you read the docs?
Read the description
And yes, you can see in the example that they use it differently from you
"Use this to create a rotation which smoothly interpolates between the first unit quaternion a to the second unit quaternion b, based on the value of the parameter t. If the value of the parameter is close to 0, the output will be close to a, if it is close to 1, the output will be close to b."
from what I am understanding
take point a (my current rotation)
take point b (take the location of where i want to move to and grab the rotation that would cause me to look)
but im confused on wtf T even is, if it's not the rotation speed
Yep, that. It means that you need to change t overtime and needs to reach 1 eventually, if you want to get an output that is equal to b.
It's time of the interpolation
Do you understand what an interpolation is?
Imagine a slider going from 0 to 1. t would be the value where that slider is currently at.
If you want to slide it to 1, t needs to be 1.
Interpolation is taking two values and returning a value in between them based on t, where 0 would be equal to a and 1 would be equal to b.
ah i understand, i never knew what slerp did
im using this to make "frisbee" come to a stop but for some reason it doesnt work if (collision.CompareTag("stop point"))
{
Debug.Log("STOOOP NOW");
frisbee.GetComponent<Rigidbody2D>().velocity = Vector2.zero;
}
so i need T to gradually move t from 0 to 1 over time from the point of pressing the key to when it starts to move in game
If it's 0.05, that would be 5% between a and b
frisbee is a prefab
Yes
Lerp
Lerp?
please format your !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.
stands for Linear Interpolation
im using this to make "frisbee" come to a stop but for some reason it doesnt work ```
if (collision.CompareTag("stop point"))
{
Debug.Log("STOOOP NOW");
frisbee.GetComponent<Rigidbody2D>().velocity = Vector2.zero;
}```
Well, you can start with how they do it in the example
slerp or lerp? im confused
Either one. The way you use them is the same
okay
That being said, in your case you might want to use a different function
how come?
One that moves the rotation by a flat value
is the stop point a trigger? does it actually have the tag?
is the script on the object?
Because your a is constantly changing
okay im getting confused can we walk through this from the top
"it dont work" isn't a detailed enough description of the problem
my a is my current rotation
my b is the rotation i want
my t is the timeCount, which is where in the "slider" my rotation is currently sitting
my a and b are always changing, so you want me to have a fixed rotation value
yea the debug.log works but the rest doesnt
but i don't understand how that makes sense if you told me that having a fixed value where timecount goes is my issue
- You're using lerp/slerp incorrectly.
- You're doing it because it doesn't suit you use case.
- There are better ways to move rotation fitting to your needs.@summer pilot
what exactly happens to frisbee when you get that 'stop now' message
if (collision.CompareTag("stop point"))
{
rigidbody RB;
Debug.Log("STOOOP NOW");
RB = frisbee.GetComponent<Rigidbody2D>()
RB.velocity = Vector2.zero;
}
try this
wrong reply
it keeps mmoving
please explain, i dont get it
there is no functional difference between this and what they have
i feel like im understanding how slerp lerp works
i see that now thats why i replied to him in the manner i did
but its not usable in my case?
yea nothing changed
could it maybe be because the frisbee is a prefab
Is the frisbee maybe receiving a constant force thats overriding this change?
can you send the full code
oh yea that probally it
Good. What I'm saying now is that you shouldn't use slerp at all in your case.
you could be modifying the prefab instead of the instantiated gameobject
what should i be using instead?
Go back to the documentation and open the Quaternion page. Look at what methods it has available and what they do. See something fitting?
Tip: look at the static methods.
ill have a look
Angle & FromToRotation both seem they could work?
What about RotateTowards?
While you certainly could do it with angles, that would just make things more complex than they need to be.
i got a var in the update method that i cant use in the trigger for some reason do you know why
no because you haven't sent the code
mb mb
beware youre gonna be looking at spagheti code
im trying that now, but when i try to input the step var, i get this issue
you have multiple PlayerController classes imported, both with the speed field
It says you've got two speed variables declared
Showing the console window might reveal other issues that you've got
Sounds like you have 2 speed fields.
yep, i spaced that sorry
{
if (Input.GetButtonDown("E"))
{
Debug.Log("e");
var pllayertrans = frisbeetransform.transform.position;
var bullet = Instantiate(frisbee, frisbeetransform.transform.position, frisbeetransform.rotation, gotothis.transform);
if (isfacingright == true)
{
bullet.GetComponent<Rigidbody2D>().velocity = frisbeetransform.right * frisbeespeed;
}
if (isfacingright == false)
{
bullet.GetComponent<Rigidbody2D>().velocity = -frisbeetransform.right * frisbeespeed;
}
}
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("stop point"))
{
Rigidbody2D RB;
Debug.Log("STOOOP NOW");
RB = frisbee.GetComponent<Rigidbody2D>();
RB.velocity = Vector2.zero;
}
bullet is the right var
how is update even being called?
its not written correctly
do you have your IDE configured?
Is this real code and not pseudocode? Update needs to be capitalized.
player doesn't rotate at all now :/
public class PlayerController : MonoBehaviour
{
public float playerSpeed;
private Vector2 move;
public float rotateSpeed = 1.0f;
public void OnMove(InputAction.CallbackContext context)
{
move = context.ReadValue<Vector2>();
}
void Start()
{
}
void Update()
{
movePlayer();
}
public void movePlayer()
{
Vector3 movement = new Vector3(move.x, 0f, move.y);
var step = rotateSpeed * Time.deltaTime;
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(movement), step);
transform.Translate(movement * playerSpeed * Time.deltaTime, Space.World);
}
}
i rewrote the update part because i didnt want to also send the part of the code that has nothing to do with this
!code post the whole 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.
Declare the variable as a class field and assign it in Update. Then attempt to use it in your wanted method if not null. You shouldn't be polling for components though - something looks unreliable.
im suspicious of 'frisbee'
Try increasing that speed parameter to something like 180.
the rotation speed?
Yes
Is frisbee set
wdym
in the inspector
rotates v slow (fixed by turning the value up to 500), but still rotates back to north position after i let go of the controls
yea
Reference the object as the common and specific component type to avoid having to make get component callscs public Rigidbody2D frisbee;You can always access the GameObject component with the gameObject property - cached and faster than a Get Component call.
yea
alr
Could someone please help me? I'm feeling very stupid and confused
depends
was about to grab the link too haha
I've disabled my pause menu button start and I use a script to turn it on at runtime
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PauseActivator : MonoBehaviour
{
[SerializeField]
private Button pauseButton; // Assign this in the Inspector
void Start()
{
// Ensure the pause button is enabled
if (pauseButton != null)
{
pauseButton.gameObject.SetActive(true);
}
else
{
Debug.LogWarning("Pause button is not assigned in the inspector.");
}
}
}
and that works well enough
but this ONLY works on one scene
every other scene, the pause UI has to be enabled otherwise the buttons inside it won't work when I load into that scene from the start
I really don't want to have to disable and enable the menu every time I leave a scene in the editor
Also, if you're trying to stop the instance of a frisbee maybe the trigger function should be on the frisbee object instead of this object. Else check if the frisbee made contact with this object (assuming this is on the player - implied by naming conventions: player script) and access the component (rigid body) on the other object to modify its speed and whatnot.
i wonder if its something to do with changing the velocity outside of fixedupdate
i have no idea what you're trying to do tbh
can you describe your goal?
nsh i kynda want the frisbee to float in place
agreed ngl, this is my 5th time reading over it XD
idk man
pause menu button start is a lot of words
I'll need a min to break down what I'm doing cause there's a few steps (I haven't made a pause menu before)
I'd say also enable/disable the ui on runtime?
if you can't describe your goal, you should take a step back
That happens because your input is 0,0 in rest position and you still calculate a rotation for that value.
how do i fix that?
It's really not much of anything, I'm just a little tired
let me collect my words
i don't want it to rotate when the player isnt actually moving
i get it, im just saying that taking a step back and looking at your problem as a whole will often show you the solution
describing the problem and how you're trying to solve it to yourself also helps with that
I've got a pause button. Inside I have a single option to mirror the gameplay (it's for mobile and it makes it easier to play left handed). I am putting the button in the pause menu so that it's always accessible but not in the way.
That button must ALWAYS be enabled when a scene is loaded otherwise it won't work. Enabling it once you're in the scene breaks it. Therefore the pause menu must also be active otherwise the button will still not work.
My idea was that if I enabled it at runtime then I could get around this. This idea works ONLY at my first scene. If the pause menu is disabled in any following scene then the button to mirror will not work.
If the pause menu is enabled in any subsequent scene first, then it all works fine!
But now I have the issue of the pause UI ALWAYS needing to be turned on (which blocks the editor)
hmm that makes sense in a logical way
why does enabling it once youre in the scene break it
Oh that's easy to explain
I have my script search for a component (by string in this case)
it's not good but it works in a pinch
why
however if any of those listed things are disabled, then it can't find it
I tried doing a serialized field
but that works even less
not sure why
ok first off you can reference the main camera with Camera.main
there's no reason to even have the first thing
Heard of the Singleton system before?
no
Look it up, it's usefull
The script uses PlayerPrefs because I wanted the setting to be persistent across scenes
when I use a SF, the game just forgets what's supposed to populate the field and leaves it empty
What?
DDOL is better for inter-scene persistence. Use playerprefs only for inter-runtime persistence
Ok first
[SerializeField] Camera secondCamera;
did you do it like this?
yes
ok and you filled the slot in, what do you mean it forgets?
Then make a check and only rotate it when the input is not 0.
@sand heath I use using a DDOL method before, but the field would be blank when I went into a new scene
how do i get my input value as a variable?
because the cameras dont transfer to the other scene
What's DDOL? o_O
Don't Destroy On Load
dont destroy on load
I've got a copy of the camera's on every scene
ah that makes sense ty
so that wasn't the problem
that would be the problem
just because you made an object that looks the same doesn't mean it is the same
even if its a prefab
Oh I see, because you need a reference to the new scene
so when you go to a new scene you need to set those fields again
You already have it in your code though. You wouldn't be moving at all if you didn't have it. Think.
main camera you dont need to worry about, second camera i guess is fine to find by name but its really not optimal
you could find by tag which would be much faster
I'm taking some time to optimize these systems before I move on
Sounds like a good plan
so if there's a better way to do it, that's what I need to do
not a bad idea
what do I do about the button, though?
OH THEY TAKE TAGS TOO
wow
what do
thats like asking about if the bobble head made it in a car crash
What does that mean? XD
whatever the problem is is deeper than this button 😭
I'm worrying about the wrong thing
something like this i presume?
but i have an error, how else would I right "does not equal"
console log would say true
movement != Vector3.zero
I'm trying to make a pause menu that has a persistent setting inside it
this worked beautifully
Vector3.zero equals new Vector3(0, 0, 0), or 0 btw
Alright we'll start with how the pause menu works
Is it just a prefab you have in every scene?
they ain't even prefabs
the camera's aren't, atleast
neither is anything in the UI
why not
if you ever use an object more than once and you need changes to be synced you should use a prefab
all gameobjects can be prefabs
a camera is literally just a gameobject with a camera component on it
so should both the Main and Second be prefabed?
refer to what i said earlier:
alright that's done
are they identical?
do you want them to stay identical across all instances?
yes
then prefab
Done
could anyone help me figure out why my game object isnt centered? when i put my game object at (0, 0) it isn't in the center, but things like my camera are centered at (0, 0)
SF them next, I assume?
is it a child under another object?
is it a child of another gameobject
is it a child of another GameObject?
well like i said earlier, serializedfields wont persist between scenes because the cameras dont persist
the sprite is broken up into both a child (the base) and the tower itself as the parent, but they are both at 0,0
oh so then I should use tags?
whenever you load into a new scene you need to update those fields
yes use a tag to find secondCamera
main camera can be found by camera.main
where is the pivot located on the GameObject?
how should I tag my UI? Just call it all "UI"?
you dont need to tag everything
only tag things that need tags
well the pause menu needs to be found across scene, so that should be tagged shouldn't it?
or atleast the specific button within it
is the circle the pivot? thats almost in the center
well the pause menu could be a singleton
no, that looks like the collider. the pivot is located where the handles appear: to move, rotate, or scale the GameObject . . .
i meant the small blue circle near the center not the green one
yeah. just select th emove tool to see where the handles appear. that's the pivot/center of the GameObject . . .
can you show us the scene hierarchy to display the GameObject?
public static MyClass Singleton {get; private set}
private void Start()
{
if (Singleton == null)
{
Singleton = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
@sleek marten
then accessing the singleton:
private void Update()
{
if (Input.GetKeyDown("P")
{
MyClass.Singleton.MyMethod();
}
}
@sleek marten
Oh no that means I have to redo this pause menu code 
untangling it to fit this in would probably take longer
Not like it works rn lol
Surely you have version control set up
They never do
what position appear from the inspector?
0,0 for both the base and the tower
Have you tried just following a tutorial first
I'm assuming you have
But it broke down at some point
yeah and they're all 6 years+ out of date or go over things that I'm not doing
The only thing that might be outdated is input
Pause menus are pretty straightforward
yeah that's what I thought too
it's really cause of this button, I think
and it's weirdness that I have to work around
I think fixing that will make the other stuff easier
right underneath "Scene", change "Center" to "Pivot". does it change the position at all?
okay, that's the actual pivot. before, you were on "Center" which moved the handles to the center of the GameObject, not the actual pivot location . . .
can i move the pivot to a custom point?
yes, use the sprite editor . . .
@sand heath thanks for the help! I'll be busy for the next day or so getting this sorted
god willing I only have to address it once
Don't worry you'll have problems like this every day
Where you realize the way you were doing something was wrong and you have to redo it
That's what I'm expecting for about everything I have so far since I'm in the "just make it work" stage
I'm getting it ready for future proofing, which starts with a functioning pause menu
found it, Thank you!
i would ask this question in #💻┃unity-talk
Oh ok
Oops wrong channel
what does <> in class declaration mean again? e.g. public class Grid<TGridObject> { { }
is it related to generics?
Yeah, it's defining the type that's been used for the generic
public static List<char> alphabet = new List<char>
{
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
};
foreach (char letter in stringCode.ToCharArray())
{
Debug.Log(letter.ToString() + " - " + alphabet.IndexOf(letter).ToString());
newSeedCode += alphabet.IndexOf(letter).ToString();
}
alphabet.IndexOf(letter).ToString() is returning -1 and I'm not sure why?
a quick google didn't pop up anything about indexof returning -1 and I haven't seen that before
Quite literally the first few lines
You probably don't have that character in the alphabet list
I didn't know certain types had specific stuff like that, was looking at indexof in general apologies
Yeah just found it tyvm
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
I'm using 3d tilemaps for a 2.5d game I'm making, using the gameObject brush for walls. is there equivalent to the tilemap collider for a set of gameobjects? or a way to bake the gameobjects together once I've placed them all
does anyone have a 2D character state system that i can have? lol
basically for when your character get snared or knock back
yup youre definitely creating a list of generics there. I am asking about use of <> on the first lines of class
my question was unrelated to my answer to you
thanks
Keep in mind that a List IS a class
public class List<T> is the class definition.
public class List<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.IList
...(somewhere in Start())
foreach (Transform slot in inventoryParent)
{
if (slot == null)
{
Debug.LogWarning("Found a null slot in inventoryParent.");
continue;
}
_slotPositions.Add(slot);
Debug.Log("Slot added: " + slot.name);
}
Debug.Log("Total slots added: " + _slotPositions.Count);
...somewhere in the code
foreach (var slot in _slotPositions)
Why is _slotPositions null?
Where was the error thrown? Show the complete error
What is wrong with my code? I'm trying to keep my player with from getting out of bounds, but when he reach's -5 on the x position the player will get teleported to -5 on the z position too, same thing in the opposite direction.
Messed up a bit, looks like slot returns null, but... i don't really know.
Looks like a lazy/bad copy n paste.
if that's line 42, _slotPositions is null
Man, I've been doing the unity learn courses I don't know any other way.
I'm just beginning
Yeah, it's null at start, but I'm adding something here, so why would it return a null?
The list must be initialized before you can add things to it... When you're working with reference types, variables just store a reference to them. Declaring a variable for a reference type just creates a container for that reference - but you still have to tell it what it should reference
May not be the issue, but those should likely be else ifs
okay, I will try that
That was a bit of a mess of an explanation on my part 😅
Maybe you could explain it a bit simplier? English is not my main language, and I didn't understand 80% of your message, especially since I'm kinda new to C# 😓
The else if didn't help although it was a good suggestion, you also for some reason can't keep the player within the zposition you want him.
A "variable declaration" is just creating a variable with a type and a name:
List<float> foobar;
I now have a variable foobar. The type of the variable, List<float>, just describes what value the variable can hold. So I've sort of created a "box" that can hold a specific thing, but there's still nothing in it.
Right now, the value of foobar is null. It can refer to a List of floats, but I haven't told it which List of floats it should refer to. There's no value. The box is empty, because we haven't given it any value.
"Initializing a variable" is assigning a value to it for the first time. If I want it to refer to a brand new empty list, I have to write code to explicitly create that list, and then assign it to the variable:
foobar = new List<float>();
Now foobar is no longer empty - it refers to that specific empty list.
Of course it shouldn't have been so detailed, but thanks, lol
I'm more interested in the word "reference", I hear it often but don't understand its meaning in C#.
I sort of enjoy trying to simplify and verbalize things I think I know... it's good exercise 😁
Did you ever get this fixed?
No
Should the second two conditions not be checking the z position? They are checking whether the x is within the zRange
they are, how come they are trying to check x? Because it is checking for zRange
OHHH sorry
A reference can be thought of as an address. It points to a place in memory. The different things using that address will all "see" the same data
Value types will copy the data and see their own copy
I guess I'm just blind
Easy mistake, no worries
thx for the help
When we create a variable, it's associated with a specific address in memory.
"Value types" are usually simple data like floats and are stored directly at that address. Assigning the value of one such variable to a second copies the value into second variable's address - so they're both unique:
float a = 5.2f;
float b = a;
a = 6.5f;
Debug.Log(a); // 6.5
Debug.Log(b); // 5.2
Meanwhile more complex data is usually a "reference type," meaning that instead of directly storing the value at the variable's address, it may be stored elsewhere, and the variable just holds the address of where it actually is. So our variable is just a reference to it.
When you assign one reference type variable to the other, it copies the address of the data into the second. So now they both refer to the same data instead of unique copies:
class FooBar {
public float baz;
}
FooBar a = new FooBar();
FooBar b = a;
a.baz = 3.14159f;
b.baz = 42f;
Debug.Log(a.baz); // 42
Debug.Log(b.baz); // 42
Ah, thank you so much
NP... My description of the addresses in particular may not be entirely accurate, but I think may be fine enough for a broad overview 👀
What are the "< >" when I use GetComponent<Foo>() or public event Action<bool> Bar
Type parameters.
They specify the type when using a function or creating an object
Here is an article that goes more in depth. :)
I guess what im curious is about is why isnt it GetComponent(foo)
Ill read that for sure
The reason is that it is implied. C# automatically detects the type needed for it.
if you did
MyMonoBehavior fee = GetComponent(foo);
It would work. But if you did
var fee = GetComponent(foo);
It would need a type parameter.
Can I access Inventory from scene on prefab without creating a new one in the prefab itself?
The Inventory is in the scene, and you want something in the prefab to reference it?
Yup
Nope - prefabs can't hold references to anything in a scene.
Ideally, you should assign that reference on the clone when the prefab is instantiated
Could something like this work?
FindObjectOfType is not the best practice.
Yup, I understand, that's only the concept. What would be better to use?
Depends on context
You can have a static variable, and have the inventory assign the variable to itself when it starts. You can have the object create an inventory when it spawns in. Etc.
Hey guys! Hope y'all are doing great. I'm struggling with predicting a trajectory of the game object.
Currently, what's happening is that the trajectory is drawn AFTER the game object moves. I want it to be predicted. The code I'm using for the trajectory is:
public void EstimateTrajectory(Vector2 force, Vector3 startPoint, Vector2 minForce, Vector2 maxForce)
{
Vector3 velocity = (force / rb.mass) * Time.fixedDeltaTime;
float flightDuration = (2 * velocity.y) / Physics.gravity.y;
float stepTime = flightDuration / lineSegmentCount;
for (int i = 0; i < lineSegmentCount; i++)
{
float stepTimePassed = stepTime * i;
Vector3 movementVector = new Vector3(
velocity.x * stepTimePassed,
velocity.y * stepTimePassed - 0.5f * Physics.gravity.y * Mathf.Pow(stepTimePassed, 2),
velocity.z * stepTimePassed
);
points.Add(startPoint + movementVector);
Debug.Log(points[points.Count - 1]);
}
lr.positionCount = points.Count;
lr.SetPositions(points.ToArray());
}
And I'm calling it in another script like:
tt.EstimateTrajectory(maxPower, transform.position, minPower, maxPower);
Could anyone please help fix it?
Instantiate() returns a reference to what was instantiated. I usually prefer to assign the value on the new clone via that reference, unless I have some specific reason to do otherwise, or it's something handled by events.
Point to be noted is that I'm moving the game object through "Slingshot" or... "Hold To Shoot" mechanism as attached:
So something like this?
Sure that would work. There is a shortcut though...
Would like to hear it
Instantiate() can also take a component on the prefab instead of the prefab's root game object, and then it will return a reference to that component on the clone. So it sort of saves you a GetComponent() call.
public NPCController Prefab;
// ...
NPCController npc = Instantiate(Prefab);
npc.inventory = whatever;
Here I've still dragged the prefab into the Prefab field in the inspector, but instead of referencing the GO it will reference the NPCController component on the GO.
It causes me inner pain seeing you capitalize “Prefab” 🥲
Could anyone help on this please? 😅. I've been stuck for 2 hours now. And now the only issue is the order of the trajectory
Thank you!
Are you using Unity’s built-in physics?
Yes. Mainly vectors, velocity, gravity, and force. that's it
And I don't want the trajectory to display bounces. I only need just 1 curved line as in angry birsd
My naming conventions have been all over the place 😅
But Unity/dotnet conventions both suggest PascalCase for public members, so I've finally given in 🥲
(Even though Unity APIs don't always adhere to that
)
I only do mutilators pascal case. But IG public variables having mutilators is uncommon
So, upon logging the force and velocity values. They are correctly collected and obviously the points would be calculated accordingly. But... It's probably not the case when I debug the "points" of the trajectory
They're all the same 
Anyway, why are you multiplying the formulas over time if you are doing it as a prediction?
So, the idea is that...
- I pass the force applied on the ball to the function. This is being calculated accurately.
- Using this force, I get the velocity and the time of flight.
- As for the multiplication, well, the trajectory of x axis stays the same over time. Only thing affected is gonna be the y axis. That's where I have used the formula.
- So, whatever point I get, I'm adding it to the points for line renderer and that's it
The start point is the location of the ball from where to start predicting the trajectory
I just noticed I don't even need to pass min or max force as it's already calculated and clamped 
Like... in another script, I'm doing this:
if (Input.GetMouseButton(0) && distanceX <= 1 && distanceY <= 1)
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = offset;
currentPoint = cam.ScreenToWorldPoint(mousePos);
force = new Vector2(
Mathf.Clamp(startPoint.x - currentPoint.x, minPower.x, maxPower.x),
Mathf.Clamp(startPoint.y - currentPoint.y, minPower.y, maxPower.y)
);
pt.RenderLine(startPoint, currentPoint);
tt.EstimateTrajectory(force, transform.position);
}
This script is attached to the same object
So, the trajectory should be calculated as long as the mouse is held. But idk if i'm totally correct. I started 2 weeks ago 💀
After some time of debugging, I roughly understood the problem. I have _itemGameObject, it works great, but once GO moves to another parent - it's just becomes null (still not sure), giving me NullReferenceExecption.
I tried doing something like
if (transform.childCount != 0)
{
var child = transform.GetChild(0);
if (child)
{
_itemGameObject = child.gameObject;
}
}
But it doesn't seems to work
dw about the distanceX or distanceY. They are not related to the trajectory but to the pulling of the ball's mechanism. So, this if statement is triggering just not the "EstimateTrajectory" as intended
Just to be clear, which line in the video is the prediction line?
All of them. I wasn't clearing the points earlier to demonstrate what was happening. If I clear them, the trajectory doesn't form at all because on mouse release, the line is supposed to go away.
Basically, I just want the line to be drawn BEFORE the ball is released, not after which is happening rn 💀
The formula’s in the function use math for the current force that is being applied to the ball
Yes precisely. So, the amount of pull will affect the trajectory.
But... it doesn't 🤡
Start Point is from where I start pulling the ball, and current point is the point where the pull currently is located. Slingshot mechanism tbc
DistanceX and DistanceY are ONLY there to ensure that the pull works only close to the ball, not anywhere else on the screen
Are those prior errors just the same ones over again from you repeating the same interaction?
Well... it's weird that now I multiplied the force by a factor of 5 and... I got 4.01 and 4.02 💀. I'll try a bigger factor to see if trajectory makes up
Yup
Okay, cool. Just making sure 👌
I'm not sure I see how these snippets are connected though, or which line is the one the error refers to. Could you post this script on like https://gdl.space?
Also fixed by changing the signs in the point formula
Now, just gotta make sure it lines up with the actual trajectory 😂
Ah
oops
Hey, I'm really new to coding and I have a small problem with the following code:
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
public float Move;
public float speed;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
Move = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(Move * speed, rb.velocity.y);
}
}```
So, I `GetAxisRaw("Horizontal")`, right? And this code works fine, the only issue is that `"Horizontal"` is mapped to `Q` and `D` in the input manager, but when I launch my game, it uses `A` and `D`, I've tried with `"Debug Horizontal"` and it has the same problem. I've tried remapping `"Horizontal"` to `J` and `L` and it worked fine, but `Q` always bugs out and uses `A` while in game, this shouldn't be a keyboard issue as it normally works fine.
P.S. : I'm on an AZERTY keyboard with an AZERTY config.
try turning "Use Physical Keys" on and off
I'm not experienced with drag events, but I'm sort of wondering if like... since the drag handlers are on the inventory slots instead of the item being dragged, if the callbacks are firing on different slots. Like, if you drag the item from SlotA to SlotB, if OnBeginDrag is called on SlotA, and OnEndDrag on SlotB... I'm struggling to find other reasons for a null exception
You might throw some Debug.Log()s in at the top of either method and pass in gameObject as the second argument, so the logs link to their respective game objects, just to check
Need opinion on it lol
Like... it's got a good touch to it? Or I could improve more things
maybe you could chnage ther angle of the camera
That's gonna be up to the UI/UX designer in my team. But.. about the trajectory? The yellow one
I just finished up designing that.. so, what do you think? 😂
pretty good ngl
I definitely like the feedback
😁 🫡
From the trajectory?
Yeah, it makes it feel more responsive 👍
It exists while dragging, then after putting it back into the slot and trying to drag again... bam.
maybe add a toggle optoin to see the trails of the trajectory
Coolio! 😀 . Thank you 😄 ! I'll see if I could improve it further and kinda add more juiciness 😋
Wait, what do these Debug.Log() calls look like?
Debug.Log(_itemGameObject.gameObject);
Input.GetKey(KeyCode.LeftControl)
Why is this not getting detected?
Do like
Debug.Log("OnBeginDrag", gameObject);
Debug>log("OnEndDrag", gameObject);
This will add a little link to the log message which will highlight the respective inventory slot GO in the hierarchy. I'm wondering if, for one drag interaction, those game objects might actually be different
Can't say based on that code alone - it looks fine
{
Debug.Log("Sell all");
EventManager.StartSellAllItemsEvent();
}
else if (IsHovered && TownController.Instance.InTown && Input.GetKeyDown(KeyCode.S))
{
SellItem();
}```
My else if triggers properly, my first if doesn't trigger
And then
So if I hold shift and press s, while not hovering an item nothing happens
When I'm hovering an item it just sells that single item, but doesn't show the debug message for selling all
looking at the full code you posted earlier, so not sure if u fixed it
nearestSlotInventorySlot.item = _currentItem;
but you never remove it from the old slot I think?
Huh. Maybe I've forgotten how that second argument works, lol. I'll have to play with that when I have Unity open again. I guess the instance ID might be more useful anyway:
Debug.Log("OnBeginDrag: " + GetInstanceID());
Debug.Log("OnEndDrag: " + GetInstanceID());
Debug.Log("OnDrag: " + GetInstanceID());
Now it has no errors, but item doesn't follows mouse pos
I mean, there's still error on end drag
I think your input stuff looks fine... You make a simple if to test it:
if (Input.GetKey(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.S)) {
Debug.Log("Shift + S pressed");
}
Also not sure about this part:
nearestSlotInventorySlot.item = _currentItem;```
You set both to _currentItem, what's the logic there?
damn, github copilot added an ! before my towncontroller check -_- thx lol
item is used for debug by me
just forget to remove it
it's definetly a strange way of debuggin'
but that doesn't really matter
I literally just implemented the same thing for my items yesterday and it gets pretty complicated -_-
Well that's trippy... Sprinkling around some Debug.Log()s shouldn't change the behavior. Did you drag from one slot to another? Could you share the current state of the code again?
No, I mean-
After adding this line
So first I'm making it null
And only then setting the current item
So it's leaves from first slot
Oh sorry I missed that interaction
You would only want to set the original slot to null once the item has been put into the new slot
It is already like that
!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.
Here is my implementation if it helps:
https://gdl.space/yaroyayune.cpp
nearestSlotInventorySlot._currentItem = _currentItem;```
you want to set InventorySlot._currentItem of the OLD itemslot to null AFTER you assigned the item to the new slot
otherwise your inventory would think the item is in both slots
I have this logic on my Item btw, not in my inventory
you're dragging the items not the inventoryslots right?
So just put it in the end of condition?
Yup
I need to go to bed imminently, but my best guess is still that it stems from the drag handling being on the inventory slots rather than the inventory items... If that's true, if you return the code to the state it was in when you could drag items around but keep the Debug.Log()s as they currently are, then the instance IDs which get logged will be different when you drag the item from one slot to another.
And if that's the case, you might consider switching to drag handling on the item rather than the slot. You could keep it on the slot, but I feel like the logic is more complex than the alternative
Ughh guys... I just enhanced my trajectory to display more and...
tt.EstimateTrajectory(50 * power * force, transform.position);
Why do I have to multiply it by 50? 😭😂
The trajectory is 100% accurately working... lemme show you
But this factor of 50 is kinda weird 💀
https://www.youtube.com/watch?v=BGr-7GZJNXg&t=561s
that's what I used, it explains everything pretty well imo
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=BGr-7GZJNXg
Let's make a very simple Drag and Drop in Unity, great for an Inventory System.
Simple Inventory System in Unity (Store, Use, Stack and Drop Items)
https://www.youtube.com/watch?v=2WnAOV7nHW0
If you have any questions post them in the comments and I'll...
So it seems like it's kinda... can't get components, since I'm getting the components only at start.
106 and 76 has _itemRectTransform has _itemGameObject respectfully
I don't think that's the case
Mine drag 'n drop system is basically the same
Except his only has the slot handling OnDragEnd and your slots are trying to handle all of the events... I still think you should test the instance IDs 😅
Of what exactly?
Of the slots where these events are occurring #💻┃code-beginner message
My theory is that you start dragging an item, and everything is set and fine. Then you move it over another slot - now that other slot's responsible for OnDrag/OnDragEnd. But that slot doesn't have a _currentItem or a _itemGameObject. It's not at all aware of the item you're dragging, because all of that data is in the other slot alone. So it throws NREs.
I think I already showed you Instance ID's already?
...
Debug.Log("OnBeginDrag: " + GetInstanceID());
...
You did, but only after you simultaneously applied the changes based on what Pasc mentioned, which broke item dragging
Without that one line
Yep
That confirms it
The slot which handles OnDragStart is different from the slot handling OnDragEnd, so they don't have access to the same fields
thus the NREs
How can I fix it then?
Wait I might have spoke too soon - there's two different drag interactions in those logs. 😮💨
If the OnBeginDrag and OnEndDrag IDs for one interaction moving an item between two slots match, then I'm wrong.
I think using a script on the inventory item to handle some of these events would simplify things in any scenario, akin to what I assume CodeMonkey does
So basically I can create a drag 'n drop script, and then assign it on the _itemGameObject after creating it?
yeah!
I've got to get to bed though. I'm sorry I wasn't of more help here, and for possibly leading you on a goose chase 🪿
Godspeed 🫡
i cannot, i simply cannot make this up
same. exact. code.
same. exact. configuration.
the one that changes to sample scene DOES NOT WORk
W H Y
I have this foreach loop, that for some reason breaks at line 31 and says that "object reference not set to an instance of an object"
if i disable the main menu scene it still works from the sample scene, but if i try to move from the main menu to the samplescene the button WILL NOT WORK??
the text isnt a raycast target, the button is activated, the script is right ???
tilegameobjects is null
wait i might be stupid
It shouldn't be
yeah im stupid nvm, help the other guy
where to you initialize the List ?
If it breaks, can't you inspect all the variables in the debugger..?
yes, declared but NOT initialized, therefore null
That would be where you've declare it not where you've initialized it
And see what is being null
Ahh, how do I initialize it?
= new()
= new ...
But the other list works just fine
You can do so during declaration or in Start etc - in your case during declaration should be fine.
You've likely populated it from the inspector, implicitly creating a new instance.
Ohhh
the other list is public, it is initialized by Unity
That makes sense
no object with that tag
the object is in another scene thats currently unloaded
then how do you expect to find it?
the crazy part is the game works somehow???
null ref will not srop the game just make pausy unusable
ok well i need to refrence the code inside the object with the tag resume canvas, can i somehow keep it loaded in the same scene?
unload everything else EXCEPT that
DDOL
huh?
Dont Destroy On Load
Line twelve has a great amount of potential to blow up during runtime. Consider not relying on Find calls but instead: properly reference objects, use Singleton managers and whatnot.
or at least split the line in 2 and check for null
Sorry for late reply, i was asleep and i dont have any other that i recommend. Pixilart is the one i always use 🙂
the only reason i put it there is because my game seems to not work if i load it by loading the scene when the game starts
i deleted the error code and now it works?? but only once?????
ill start in the main menu
start game, game works, ill QUIT to the main menu, start the game AGAIN and this time the timescale is 0???+
nothing in the code that makes it 0
im completely lost
first image is the code that runs at the main menu that sends you to the game, the second one is the button that sends you to the main menu
im stupid wait
fixed?
fixed
I swear to god, I'll see this error in my nightmares;
(DragDrop script, OnEndDrag event)
Debug.Log(Inventory);
why is inventory returning null?
I gues you are talking about dragdrop.Inventory, it will be null if slots <= 0.
Also you should not be setting it inside the for loop
I can't set it outside of the loop
There's not one slot in the inventory
why not?
but it is always the same value irrespective of the number of slots you just set the same thing again and again
and it doesnt get set at all if there are no slots
why not?
I moved it outside of the loop; now it's setting only for one slot
It's more than 0 slots
i wouldn't name the variable
the same as your class name tbh
but you only have one dragdrop
not based on that code there wont be
I'm still working on the code, there will be
Right now I have a problem
What the hell???
it returns null and not null at the same time
show the code
if that is actually the case then you have 2 DragDrop instances active
is there any way i can make my animation run at a certain fps?
i make my object rotate left and right only !Grounded (it's a car) but sometimes it land flipped or by side it's considered Grounded and won't let me rotate how i can change the script from !grounded to !grounded + can rotate when it's not fully grounded like i said (for example it can rotate while it's not fully grounded) idk how to do it anyone ?
You gotta show the current script
if (!isGrounded)
{
// Rotate around Z-axis when in the air
float airRotateDirection = 0;
if (Input.GetKey(KeyCode.Q))
{
airRotateDirection = 1; // Rotate left around Z-axis while not grounded
}
else if (Input.GetKey(KeyCode.E))
{
airRotateDirection = -1; // Rotate right around Z-axis while not grounded
}
transform.Rotate(Vector3.forward, airRotateDirection * airRotationSpeed * Time.deltaTime);
}
!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.
Where is grounded being set, also are you usin ChatGPT
like that ?
This way is easier
ChatGPT is awful at programming unless you intensely guide it
Probably because the Trigger is thinking the car collider is also ground
yes exactly it make bugs alot but i know a bit so i can understand what i'm doing i'm learning ^^
yes exactly i think the only way to make script let me fix the car if it land not fully is by making the "if 4 wheel are grounded for each one " idk if there is better way then that
You have to use layers to exclude the car from being detected
like that i can move it forward and backward if grounded and !grounded
I dont know how IsGrounded is being set so I dont know how to write you an example
And using triggers for ground detection isnt good
CheckBox / Check[Shape] is the better way to do it
never used this, can a checkbox let the car only accelerate if it's landed
Its a bool, true or false, false if the box isnt detecting anything, so you can do anything you want with it
but dectecting what exactly ? collision ?
Yes
got it, can you please tell what are the bad thing for this ?
You can make use layers as well
CheckBox(center, size, rotation, layers, queryTriggerInteraction)
https://docs.unity3d.com/ScriptReference/Physics.CheckBox.html
(if Im correct) It can often miss collision detections or something / strange behavior, theres also more code required
ah ok appreciated bro thanks for the information provided it helps
Yeah
Hello, how could I make something happen only while the user holds a key down? Right now it only happens once i press it down, but i want it to always happen while i hold it down.
What's an optimal way to structure a "complex" inventory system?
I have different item types, some can be equipped, some can be put in a spellbook, other can be used on item to upgrade them, ...
When you equip an item it is removed from the inventory and put in the equipment
The spells are put in the spellbook instead and also removed from the inventory
Items can be clicked to move or dragged & dropped to inventory/equipment/spellbook if they can go there
Items are generated from combat and loaded from the server on game start
The most complex part is that each itemslot needs to know which item is in it and each item needs to know which itemslot it is in
Items can be dragged/dropped to empty slots or swapped when dragging an item on top of another item
When loading the game I want all items to be in their correct itemslot
My current system is a bit all over the place
I'm creating items in different places and mixing Inventory functions for click with the event system for dragging/dropping 😐
Input.GetKey
Can someone explain?
that is correct
It only moves when i press it down once, if i hold it down it just stays there
no, debug.log it and see
it works now,i dont think i saved but i still have a problem
if i walk off my platform is just keeps walking and doesen't fall down
yes, do you implement gravity?
then you should not be moving using transform.position
oh, then what should i use?
use the rigidbody methods
Use Rigidbody Rb in declaration
Then GetComponent in start()
velocity?
public Rigidbody rb;//assign it from the inspector``````cs
rb.velocity = transform.forward * speed;```
inside the vector coordinates, u can write the walkSpeed
theres no velocity, just angular and linear
This one works as well
Unity 6 has probably changed the name to linear velocity
Also do remember to call rigidBody methods in FixedUpdate ()
Not Update()
Unity 6 Velocity would be linear velocity: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody-linearVelocity.html
Ooh alr
okay thanks
it moves at light speed now
Use a lower value for walk speed
odd that you call it light speed, when its basically at 0, 1.5, 0.002
value/1000f if necessary