#💻┃code-beginner
1 messages · Page 329 of 1
Okay, and how do you intend to do that if you don't store the loaded data anywhere?
wdym open with inspector ? so if inspector is closed it doesnt work?
If you want everyone on the team to get a drink you probably don't just pour the gatorade directly onto the floor
you'd need to put it in a cup
where could i store it?
i dont know if its that alone but i had it open in runtime and it was working
In a variable
if i had it closed it just didnt work lmao
Probably one that you intend to re-use somewhere
var
strange , this object doesnt get disabled or anything ?
no lol
scary auto correct you got going on dang
lol its possessed i swear
is there literally no explanation
probably not the best way
did anything change
there usually is but requires 🔍
You're still not storing anything
sorry , brain is not workin 😭
what is SaveData?
why did you replace ReadAllText
ah ignore me probably, im late.
said earlier FromJson returns you the data
you changed wrong line
you're saying
Get this JSON string and try to make this object from it
this is the object you are attempting to make
So try actually thinking instead of just guessing randomly
FromJson returns an object from json. What do you want to do with that returned object
Where do you want to put it
i wanna load the returned object and im not sure where to put it
Well, do you happen to have a variable that holds an object of type SaveData that you are intending to fill with data
i dont have that 😭

i do? tf am i blind
Do you know what a variable is
yes
Can you tell me what variables you have on this object
on the SaveData object?
No, on the object this code is running on
well i have strings, ints , floats
when I am in conversation with npc I can still move my mouse any fix?
do you do anything to stop it from moving
strings , ints , floats. and im not sure if Vector3 counts
What is supposed to be stopping that from happening
Okay, so you don't know what a variable is
use separate maps with input system is a possible solution.
this dialouge is playing func
And what do those functions do
unlock if dialogue is playing
yes
yeah that's what you have your code as.
I am doingthat already
Okay, try logging something in those functions to find out what order they're being called
If dialogue is playing, dont you want it locked, not unlocked?
I want it unlocked to seletc options
i do know tho
ah ok gotcha
So then tell me what variables you have on this object
then yeah id debug log
Does anyone know why this just opens and the closes? I works fine in the Unity Editor.
strings , ints and floats
string , int and float
What do you think a variable is
so you can move your mouse which is unlocked, because your code tells you to do it
so whats the problem?
You should look at the link I sent
These are types, not variables
they are containers that hold data

Check the logs
https://docs.unity3d.com/Manual/LogFiles.html
im dumb
What's the name of the variable here?
string ioc = "my cat is cool"
I dont want to look around I want player to look at npc
Right. So why have you not told me what containers your object has that can hold data
nice 🙂 well done!
so the name of the variable is ioc and it is of type string
you keep telling digi what types you have.
ok so then your player needs to be not moving, which means you should use a bool on it
un-collapse so you can see what order they come in
So it looks like the most recent one to run is unlocking
your code is fine
then how do I lock player from looking around
they were too many so i jsut made ss and drew where the variables are
i just said, you can use a bool
I want the mouse to selct option rather than moving the player
Why are you showing me the variables on SaveData
please explain I a newbie
datastring and path
where you take the input, wrap that around an if statement which checks the value of the bool
No, those are local to the functions
What variables does this object have
And what types are those
instance is SaveAndLoadingSystem and SaveData is well SavaData
So then why did you lie
i know
Then just load the JSON into that, and you're set
smth like this? praying thats how lmao
Sure, but you don't need to make a new local variable just set SaveData directly to the result of the function
It's not gonna break anything it's just unnecessary
it still doesnt load the data taht i saved
Do you get (in the console) the log that's placed at the end of the function?
yep
I have this reddish sky right now but I want to chnage it when player does ceratin task
How do you know it hasn't loaded the data shown here? What have you tried?
yep i did lol
lemme showa vid
This does not answer any of my two questions
And a video won't be useful, debugging is required
You could see it in the inspector at least
misunderstood what have i tried with have i tried mbmb , well i tried loading the data from the load button in the pause menu and i know it hasnt laoded the data cause the players position and ammo doesnt set to the saved data
It loads, the health goes back to 50 when you hit the Load button
You're probably not distributing the newly loaded values to all your other objects
The log messages on save and load show the same JSON payloads also
how do i chnage this lighting through cript
did you try googling?
yeah
or every question you will ask here first
i tried google chatgpt all that
I dont think we can actually access this window though script
thats weird , cuz i am distributing them to all of my objects
have you tried using the get component method?
https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
havent tried asked chat gpt said it wont work
Fire up the debugger, place breakpoints in the functions that loads the JSON, and inspect SaveData after the JSON is deserialized. Compare the values to the JSON string and make sure they're identical.
and gave me this complex code
dang
thats a ScriptableObject not even just a normal script
like how do I chnage the sky color it should be smth fairly simple no???
like evry game has day night mech
all the answer I found so far are very complex
Rotating the directional light in the scene doesn't work?
I want to chnage the theme like take it from dark to chill happy mood
thats why I wanna update the skyblock mateliar
Yep that's the first result I hit too when searching for that
unity change skybox from script
ChatGPT lies.
Often
if i do get component audio source, will it always get the first one?
No
It won't reliably get the right one
It will get an audio source. There's no way to know which one
i thought there was a reason to order them correctly
yeah i'll do that
It is for this reason you should probably not have multiples of the same component
why do you have so many audio sources on one object?
i dont need to it was just a hypothetical
One source is fine for as many clips as you want btw
they are identical (left is after saving data and right is after laoding data)
That shows the string contents, now verify the contents of the SaveData variable
And make sure they're identical to the JSON string
If there are differences, then deserialization failed
hello is there channel where i can ask questions/help
About code, yes. Else browse the channel directory id:browse
yeah its about my unity script
then here is fine
seems like they are identical
Doesn't show anything, expand SaveData in the first screenshot and compare
You need to look into the contents of the deserialized class instance too
so im making 3D game and im trying to create painting logic for the game. I need to to convert the hit position to pixel coordinates on the texture. Im trying to map the UV coordinates obtained from the hit position to the pixel coordinates, but as unity beginner I have been struggling with that for hours.
i just wanted one for music and one for sound clips, i find that you can overload a source sometimes
Debug.Log("Hit position: " + hit.point);
MeshFilter meshFilter = hit.collider.GetComponent<MeshFilter>();
if (meshFilter != null)
{
Mesh mesh = meshFilter.sharedMesh;
Vector2 uv = new Vector2(
Mathf.InverseLerp(mesh.bounds.min.x, mesh.bounds.max.x, localHitPoint.x),
Mathf.InverseLerp(mesh.bounds.min.y, mesh.bounds.max.y, localHitPoint.y)
);
Debug.Log("UV coordinates: (" + uv.x + ", " + uv.y + ")");
// Map UV coordinates to pixel coordinates on the texture
int x = Mathf.FloorToInt(uv.x * (texture.width - 1));
int y = Mathf.FloorToInt(uv.y * (texture.height - 1));
Debug.Log("Pixel coordinates: (" + x + ", " + y + ")");
// Paint on the texture at the calculated pixel coordinates
texture.SetPixel(x, y, Color.red);
texture.Apply();
My debug results look like this:
Hit position: (10.49, 2.99, -0.97)
UV coordinates: (0, 0.4130424)
Pixel coordinates: (0, 211)
x-coordinates are always 0 no matter what, i dont know if even the y-coordinate is correct
seems like the player Position is different
Make sure you're looking at the values after SaveData = JsonUtility.FromJson<...>(...) is executed
If that line is yellow, it has not been executed yet
seems like both are not executed
firs ss was wrong ss
mbmb
this one is wrong as well
goddamit
here we go
they are both yellow
Line 45 has not been executed yet as I said, so the values in the Autos window at the bottom are not up to date.
Execute to the next line (F10) and check again.
Can you read and understand what I'm writing??
yeah i can
Doesn't seem like it
The line highlighted in yellow is the next executed statement, which means it has not been executed yet, so the JSON hasn't been read and put in the SaveData variable yet, so the values you see in the "Autos" window is not correct
Continue executing the debugger until line 45 has been executed, and check the "Autos" window again.
If the SaveData line disappears from the "Autos" window when you debug further, then you can hover your mouse over SaveData in the code directly to get a similar inspection tool.
okay they seem to match , the window above is SaveData var and the bottom is the debug.log line
i use this scriped for playing animations walk1 is a walking animation ,walk is a idle animation but when i pres a and d both at the same time it doesnt go back to the idle animation(walk): if (Input.GetKeyDown("d"))
{
Debug.Log("hi5");
transainimation.SetTrigger("walk1");
}
if (Input.GetKeyUp("d"))
{
Debug.Log("777");
transainimation.SetTrigger("walk");
}
if (Input.GetKeyDown("a"))
{
Debug.Log("hi");
transainimation.SetTrigger("walk1");
}
if (Input.GetKeyUp("a"))
{
Debug.Log("888");
transainimation.SetTrigger("walk");
Wrong screenshot again, I don't see the contents of the SaveData variable anymore
its in the window above
No that's your JSON string
the text visualizer window
THAT is the JSON string
I want the contents of the SaveData variable directly, not its JSON representation through the dataString variable
oh u meant this
Okay both match so the load is 100% successful
yep seems like it
The issue is somewhere else
share full !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 you still have an issue of course
It's 1am and I work tomorrow, so somebody else will take the lead
relatable debug logs
fr
Hi, beginner coder here, i created a timer, every 1 sec is 1 min in the game, works fine. Did with InvokeRepeating("TimerFunction", 0f, 1f);, my timer function is a simple hour minute +- thing. Then in this function, i have an if segment, where i check if the time is between 6 and 19 hours, its daytime otherwise night. My question is how can i modify a player stat only in night? I tried there, but then my stat modified every 1 sec when the function triggers.
you have a variable for the time?
i created a custom class like this: gameTime = new GameTime(hour, minute, day); Its updated every ingame minute
ok so then just check if gameTime is 19 or bigger and under 6
you could have a static variable which can be a bool or enum or something to hold the state of if its day/night or you can just check the time in your player and set the variable based of that
i have an enum already for day and night, like this:
void TimerFunction()
{
minute += 1;
if (minute == maxMinutes)
{
minute = 0;
hour += 1;
if (hour == maxHours)
{
hour = 0;
day += 1;
}
}
if (hour < nightTime && hour >= dayTime)
{
partOfTheDay = enumOfTheDay.Day;
}
else
{
partOfTheDay = enumOfTheDay.Night;
}
ClockUpdate.instance.UpdateClockUI(hour, minute, day);
PlayerStats.instance.decreaseStat();
}
the naming isnt great here
ye i know i just didnt know what should i create for this
and i got ideas along the way
but just check if(partOfTheDay == enumOfTheDay.Night) {speed = 5f;} or whatever
i'll refraktor the whole game, now i just try to do my imagination, then think about code and problems
someone please
asked you to share the full script , you never did
i tried that, but ofc its run every ingame minute. so first min i decrease a stat 10 / 2, then 5 / 2 etc etc.. so thats not good haha
my bad didnt see that
dont check it in this script
or in this method especially
Ooooh i see omg
you would have a GameObject definitley GameManager maybe you can have DayNightManager and one of them will hold variables for the time/state of day/ other things you need
https://gdl.space/xidolupuxo.cs was to long for discord
Yes i have a TimeManager
But now idk where should i check this
i mean it loads the data n such but the ammo doesnt change or the players position doesnt change to where he was in the save so im a bit confused on how i could set lets say the player position to the saved player position in SaveData
ok so you can either make the variables static, or better make a static instance for the TimeManager if you havent already
on your player, or you can set an event i think for if the state changes to day/night then the player can listen to it and change based on that
alright what is happening now instead and what do you expect to happen?
wdym event?
public TimeManager Instance;
private void Awake() => Instance = this;
``` would be a good way
oh ye i already have a singleton
https://docs.unity3d.com/ScriptReference/Events.UnityEvent.html but im not 100% on how to use it or if it works for what i said but i assume it should
Okay, but in my player where should i check the day/night cycle? start? update? thats what i don't know every time haha
when i pres a or d walk1 plays and when i let go walk plays (this is good) but if i pres a and d at the same time walk1 plays and doesnt stop
when you change the time
do you need seconds changed? minutes ? etc. figure out how precise you want event time to be
you should really be using something else for movement, like Input.GetAxisRaw("Horizontal") then play the animation if the value of it is != 0, would just make it much easier
hmm perhaps if i make the varaibles static , its worth the try ngl
oh thats a good idea, i shouldnt check this every minute, cuz night/day changes only in whole hours, so i should do that hourly i guess
yeah if its only hours, it makes sense to check when hour change
Invoke an event , then each script can listen for a specific time for example
thats how I do it
thought so event would be good, i have no idea how it specifically works though so i cant help with that
oh god im so bad at coding lol
thinking but still don't know what step should i do now
if you have the clock setup?
if its a custom time I generally make a struct for it
yes i have a clock, i have a UI element that displays the current time, and day. then i have an if statement for changing an enum to day/night. but these are running in every second real time which is a minute ingame
thanks it workes
I can show you my TimeManager script, if interested. I know its a mess but everybody starts somehow 😄
would help !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.
sure use links
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.
btw do you know how to make the walk animation instantly stop when i stop pressing a or d because right now the animation finsihes before playing the idle animation
oh man that site..
I know its a mess i accept tips, but i just don't want to copy paste from someone from a page
w8 then i'll upload to other
https://gdl.space/adafetalap.cs
much better
half the page on pastebin is wasted space on "Advertisement" window
sorry i always used pastebin.. always like 2 times in my life
Honestly i didn't know that considering i've been using uBlock for ages
Same as Fandom
Which everyone loathes
um yeah the ads are blocked but the idiots who made the css still wasted space on other scripts
is it a problem? i created for easier access or something like that can't remember haha
all your public variables should be Uppercase but you have lowercase
thank u didnt know that
literally
how is this legible or good css work?
I use vertical screens and prefer code be vertical
Oh
Anyway it doesn't have highlighting
So yeah i too prefer literally anything else
you need to select that when making the paste
uncheck exit time or make the transition smaller
nah its not a problem its a plus so you can actually implement a custom == method
instead of doing
timeclass.hour == preferredHour
etc..
you can do timeClass.Time == customThingAtTime
actually you said you dont need specific minutes so ig it doesn't matter for full time, checking hour would be sufficent 😛
I need help in VC. I am the worst game developer on earth. I need with C# - Unity - Multiplayer!! Please!
#archived-networking , also no one will go in a VC likely, would be better to use a video/better explanation
I do not even understand what is happening with this
happening with what
With the game developer stuff man
good 😄 and where should and how write the check for day and night? i mean i already have that enum, and works, but where to change the stat? if i put on start its only run once, if i write on update, my stat change in every frame
@deft grail Ill paypal u if u can help at this point g
how can i even run a function only in every hour?
only when it changes from day to night
make event
welp that failed miserably
crypto friendly too
sounds good
i want to give my player reward if they reacheed this end of the convo and do someother action if they reached the other end
- you didnt say what you need help with
- i dont know networking
I need help with multiplayer stuff
if you're new to event u can use UnityEvent which lets you plug in other scripts' methods to run through inspector. Much like Button component OnClick
that doesnt tell me absolutely anything
I am the worst I said
Come VC I will show you, you ask too much for my shity game dev skills
then dont do networking or hard stuff
record a video then and explain in the appropriate channel?
coding is fine, thats how i can learn right? 😄
3 weeks into unity and now I am doing networking bullshit
Easier in VC, I have 10000 problems
you chose that lifepath
Golang >>>
this isnt the server for VCs
thats not our problem though and being disruptive of server rules
Do you have a server for VC?
there is no voice channel here no
Ain't got time for money sleeper
please stop spamming channel with unrelated nosense
he left, great 👍
so if i add a UnityEvent i can pass in the enum, and when it changes it fires?
in that case you can also use a event of type Action
welp im lost , tried making the variables static but didnt work so im not sure how i can set the player health to the saved player health etc 
@rich adder can u check my ink issue
okay i'll read about that
you can make an Enum for it but I just do everything in code so use Action
its not that difficult?
i mean i have the day/night in enum
eg
public static event Action<DayNightEnum> TimeOfDayChanged
TimeOfDayChanged?.Invoke(currentEnumVar)```
here static would be acceptable since its a general time clock
this way anyone can do
TimeScript.TimeOfDayChanged += MethodToRun
oh ye i remember i saw this in a video few days ago, but can't remember yes thats what i was looking for
my SaveAndLoadSystem is a singleton so i cant get references , i was thinking of making a script that holds static variables and then set those , example set the static playerHealth variable to the non static playerhealth variable etc then set the static varaibles to the saved data variables , not sure if i explained it good sorry
you load the variables, then you set your health to the loaded variable
I would have to literally use the docs again, I havent used Ink in a few years
okay i'll have a look
they had Signals or something like type of triggers that run code when area is hit in convo
just link that to a method, again using a third party plugin while you're still learning is like juggling chainsaws while riding a bike
i wanan set the health and the other stuff to the loaded variables but well i cant cause i cant put references in a singleton
did you make it a static event ?
yes
so whats the problem here? you cant get a reference to your player?
why not
cause the SaveAndLoadSystem is a singleton
this is inside TimeManager script ?
@rich adder yes, but wait where should i put TimeManager.TimeOfDayChanged += decreaseStat(); ?
also you gotta get rid of () when you subscribe a method to an event
so why cant this access a GameObject which holds all the references, or the player access the SaveData and load them itself
this can be inside any script
that need to know about the day change
but in start, update, lateupdate?
or just anywhere?
make sure the method can receive an enumOfTheDay
- it cant cuz the
SaveAndPlayerSystemgameobject needs to be in both main menu scene and in the actual game and since the main menu doesnt have the player object then i cant put those references - i already tried and it didnt work for soem reason
the method you give it requires the correct signature so 1 arg of enumOfTheDay
your not saving or loading in the MainMenu scene so it doesnt matter if you have references
i am loading in the main menu scene lol
when i press the continue button it needs to load the saved data
then dont load it here
or have your player in this scene to and make it transfer to the next scene
?? why shouldnt i load it there?? i literally need tho
need it for what
to laod the saved data when i press continue button
but why do you need to load it now and not when you get into the main scene
how am i suppsoed to laod it when i get into the main scene?
the same way you load it now?
just do it when you get into the main scene
tell me how to check if im in the next scene or if the scene has changed?
Its still run in every seconds
where are you invoking the event?
where should i? 😄
well since it relates to enum of time of day, only makes sense to do it when you switch timeofday lol
Not sure if it will work but I guess I could give it a try
send new script rq
!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.
yeah it is lol
usually Time.deltaTime is ok
if (hour < nightTime && hour >= dayTime)
this should be inside when Hour switches +1
ideally the whole thing should be a method
line 80 to 90
instead of cramming it in 1 if statement

okay it works, now i get the Night log in every hour
you only want it done once?
As you can see with the recording, I am trying to have the camera be rotated when the gun shoots, but this is also rotating the 180 degree limit I placed on the camera
yes, i want something like my character fatigue goes down twice as fast at night
but only at night
Like when I look up completely, I start looking backwards
how do I rotate the camera but keep the clamp conditions the same?
you could make a boolean , if its already enabled then ignore the rest etc.
or could store the previous state of time of day and if its the same dont invoke etc.
get creative!
void checkDayCycle()
{
if (hour < nightTime && hour >= dayTime)
{
partOfTheDay = enumOfTheDay.Day;
}
else
{
partOfTheDay = enumOfTheDay.Night;
}
TimeOfDayChanged?.Invoke(partOfTheDay);
}```
you can do this to track both btw if you need to know if previous was day
i think i was when i created this time manager. ofc its not ideal, names are bad etc, but i figure out the whole code 😄 Now i can't do this for like 2 3 hours ( i know sometime i'll struggle for a week or month) thats why i asked u guys 😄 Thanks for the help, i tought there is something that i can do easier than booleans
nice thanks
i believe the clamp is changing because it was relative to the cameras starting position(?)
so how can I rotate without changing the clamp position?
Hey champs, I'm using the terrain system to spawn tree. On those trees, I have a script that supposed to disable the MeshRenderer on them, so the trees are invisible. The reason for this doing is because I want to spawn trees at the same location as game objects so I can use RayCast on them. Ray Cast isn't working on the Terrain system spawned trees.
Here is my script. It isn't make the trees invisible:
private void Awake()
{
// Spawn this this tree on this current trees position while also using Fishnet to spawn the tree
MeshRenderer[] meshRenderers = this.gameObject.GetComponentsInChildren<MeshRenderer>();
Array.ForEach(meshRenderers, meshRenderer => meshRenderer.enabled = false);
this.gameObject.GetComponent<Collider>().enabled = false;
}
did it yeyy,
void checkDayCycle()
{
if (hour < nightTime && hour >= dayTime && partOfTheDay != enumOfTheDay.Day)
{
partOfTheDay = enumOfTheDay.Day;
}
else if (hour >= nightTime && partOfTheDay != enumOfTheDay.Night)
{
partOfTheDay = enumOfTheDay.Night;
TimeOfDayChanged?.Invoke(enumOfTheDay.Night);
}
}
how do I rotate a camera without messing up a clamp I put on it
does this even run first of all? put a Debug.Log
and check also the meshRenderers if theres anything in it after making it
Oh smart. Thanks!
I have simplified the above code, but my essential problem is that I can't clamp it to the axis it was at initially, does anyone have any idea of how to do such a thing?
How can I rotate the camera, but the clamp remains on the same rotation as it is initially sent to?
i really dont understand how what Im doing is effecting the clamping whatsoever
because the -90 to 90 are a fixed possible rotation
How's it going? Debug.Log does get called. And meshRenderers does print that there is multiple PT_Pine_Tree_03_green_LOD . And when I print the enabled status of those mesh renderers, they come out as false.
so the code works exactly as you expect right?
All except for the trees actually hiding
But when I drag and drop a tree in the scene editor, and disable the mesh renderer on the LODs, the tree does disappear
can you actually see it being disabled in the inspector after you run the code?
I'm not sure how to inspect a tree that was spawned by the Terrain system.
It doesn't pop up in the Hierarchy
it bakes it into the terrain
actually it's been a minute since I'ved used it, but usually that's how the vegetation like grass works, but the trees may be different
The terrain system has an array. I could look through that, but not throug the scene editor I think.
Yeah, the idea is it removed the gameobject overhead, but they do become a single drawcall
I'm having trouble reading this documentation part
I'm not sure how to achieve RayCasting this one
Especially I want to know when my player hit the tree
getting the exact tree you hit may be a little hard as it combines it all into larger mesh colliders
an idea is to get your hit ray position and then make some positional dictionaries to get the nearest tree from that hit
if you want individual colliders then you may just want to place the trees yourself
Actually I may be wrong about that. Does raycasting a tree not return any collider information that's not specific to the terrain?
also #⛰️┃terrain-3d you'd probably get better answers from
Thanks Mao, I'll try #⛰️┃terrain-3d
public float horizontalMovement; (1, 0, 0);
public float verticalMovement = (0, 0, 1);
can someone tell me whats wrong with this and why when i put it with
horizontalMovement = Input.GetAxis("Horizontal");
verticalMovement = Input.GetAxis("Vertical");
it wont move up or left and right
what are them numbers in brackets
start by making sure that your !IDE is configured so it will underline the obvious errors in the code because there are several issues with the first two lines you shared
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
yeah it says there is but idk whats wrong with it would i use vector3 in replacement of the xyz?
you shouldnt be using xyz at all
that makes no sense
a float is 1 number
oh yeah
and GetAxis also happens to return a float, which is 1 number
good point
{
public float speed = 5.0f;
// Start is called before the first frame update
void Start()
{
horizontalMovement = Input.GetAxis("Horizontal");
verticalMovement = Input.GetAxis("Vertical");
Vector3 movement = new Vector3 (horizontalMovement, 0, verticalMovement);
transform.Translate(movement * speed * Time.deltaTime);
}
i changed it to this
what is horizontalMovement and verticalMovement
you are giving a value to nothing
alright
you need to do this FIRST, and follow a basic C#/Unity tutorial if you arent already
Well I had done that and I was reusing the info from the unity programmer junior and now im stumped so imma just figure it out
oh i was right the code was correct i just had it in void start and not update
didnt even notice that, that would be an issue in Start yeah
which is why i suggest following a basic tutorial
alright i will
Sorry but why only one "||" is not valid meanwhile the others are?
it doesnt recognize the others yet i guess
you have closed the if statement then trying to continue to put code after
also should be using Input.GetAxisRaw("Horizontal") and Vertical instead for easier input, or use the new Input System
nvm you are
Yes.
just this then ^
Im trying to make it so it checks whenever you are pressing WASD to activate animations.
you can just use your x and y?
i dont know how to 💀 thats why im doing it this way. although i know im just making it harder.
its just a float, just check if they are both not equal to 0
I cant send the gif i want, but i wanted to send the "HUH?" cat.
yeah its banned to avoid spam
The " if (x != 0 && x < 0)
{
sr.flipX = true;
}
else if (x != 0 && x > 0)
{
sr.flipX = false;
}" is not checking it already?
You can see it here.
yeah it is
that x != 0 on both is pointless anyway, since you are checking if tis > or < 0
oh wait you are right
is there a place i can learn how to link animation and boolean parameters to my characters WASD movement
just check the docs for the things you need, for exmaple the Animator has some methods SetBool SetTrigger and stuff, you can use them for your animation things
same goes with any other components and stuff you want to do
private Animator animator;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
horizontalMovement = Input.GetAxis("Horizontal");
verticalMovement = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontalMovement, 0, verticalMovement);
transform.Translate(movement * speed * Time.deltaTime);
if (verticalMovement > 0)
{
animator.SetTrigger(WalkingUp);
}
else if (verticalMovement < 0)
animator.SetTrigger(WalkingDown);
}
}
Ok so i have this and it doesnt work if I use animator.SetTrigger or animator.Play
!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.
use InlineCode if its small or the links if its big code
if your making directional movement you can use a blend tree if i think it was called? in the Animator to make it much easier
what if its a 2.5d environment would it still work?
yeah? why wouldnt it
it just sets the animation based of values
you can pass your horizontal and vertical inputs im pretty sure
how can I rotate a camera in script without rotating the clamp attached to it
I want my camera to be moved up everytime I click, but when I do this, it also moves up the clamp
moves up the clamp?
what does that mean
show code cause I have no idea what you're talking about tbh
showed a vid up here
as you can see from the video
shooting the gun rotates my camera, but also the clamp
before I restart the game in the video, you can see the 180 degree clamp allows me to rotate all the way backwards
when I restart, you can see that it works as intended
not lettering me look upsidown behind me
the moveCam method is called somewhere else btw
should clean this up first also whats with that random Quaternion.Euler doing nothing
thats a great question, when I first started unity like a month ago i followed a basic fps cam tutorial, so it must of done that for some reason
@deft grail So i did this and did the same type of thing that it told me to do and yet it doesnt work how i want it to
how does it work and how do you want it to work?
so it either just runs the walking down and doesnt change
what else is there to clean up
other than my two random comments ig
why are you setting euler angles twice
well there should be 2 values here im pretty sure not just 1
Wym?
where it says Blend, thats just 1 value
it should be 2
for X and Y
I was just toying around with camendRotation, nothing meant to be permanent
well whats the code anyway you did to change the animation
one sec
have you ever encounter anything like this?
I use cinemachine
do you know of any way or reason why rotating in script instead of with mouse input would result in the clamp being rotated aswell?
wdym rotate in the script?
its all rotated in script
idk how to put some of this stuff into words
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class PlayerController : MonoBehaviour
{
public float speed = 5.0f;
public float horizontalMovement;
public float verticalMovement;
private Animator animator;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
horizontalMovement = Input.GetAxis("Horizontal");
verticalMovement = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontalMovement, 0, verticalMovement);
transform.Translate(movement * speed * Time.deltaTime);
animator.SetFloat("MoveX", horizontalMovement);
animator.SetFloat("MoveZ", verticalMovement);
}
else if
{
// Reset parameters to zero to revert to idle state
animator.SetFloat("MoveX", 0);
animator.SetFloat("MoveZ", 0);
}
}
it didnt work
is this the full correct perfectly pasted code?
this makes no sense
what are you using else from, has to connect to an if, its also not inside a method
nvm I figured it out
i cant be modifying the transform, which the clamp is based on
I need to modify verticalRotation
which simiulates a vertical input
oh wait one sec
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class PlayerController : MonoBehaviour
{
public float speed = 5.0f;
public float horizontalMovement;
public float verticalMovement;
private Animator animator;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
horizontalMovement = Input.GetAxis("Horizontal");
verticalMovement = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontalMovement, 0, verticalMovement);
if (movement != Vector3.zero)
{
transform.Translate(movement * speed * Time.deltaTime);
animator.SetFloat("MoveX", horizontalMovement);
animator.SetFloat("MoveZ", verticalMovement);
}
else
{
animator.SetFloat("MoveX", 0);
animator.SetFloat("MoveZ", 0);
}
}
}
looks fine, whats wrong with the animations?
They dont play
put a debug.log in both the if and the else to see if they run, you can also log animator.GetFloat("MoveX");
I have a problem that probably needs more evaluation in order to understand.
I am making a sokoban game as my first one, and so far I made the player move with WASD by 1 full object size. All walls and the player are scale 1, and there will be offgrid objects, so immediatelly, we can't store X and Y positions as variables of each object.
The problem is, that the collider recognizes a wall if I try to move towards one if the player and the wall share an axis, or a neighbouring one. You can see roughly how the detections work, and that obviously is not what we want.
Here's the code so far. This is the only script in the game so far, as the walls only have a box collider their exact size each. https://hastebin.com/share/pejunemibe.csharp
I'd do that later, but the way I'd like blocking to work is so crates are a possibility. I'd like each object that has a collider to have a function that is executed when something is attempting a push/interaction with it. With walls, nothing happens, so you are blocked if one is in the way. This means the function tells whatever tried to push it that it cannot do that. This way, crates work like this: Player attempts to move into crate -> crate checks for walls in the way -> if there's a wall, it can't move, if there isn't, it moves. -> if there is another box in the way, ask it if it can move, and repeat the process until a definitive response is given. We can use overrides for the function or something.
The previous block of text was a suggestion for if someone has time for that right now. But, really, all I need is for someone to explain what's wrong with my collision detection, and how I can fix it.
Here's also a pic of both the player and the wall objects.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
@deft grail
well there would be the problem
Ohhh
thats not how you set the value of a blend tree
Doesnt work still
show the logs again now
show the code where you put the logs
Right now I'm pressing up, I have no idea why this happens
if (movement != Vector3.zero)
{
Debug.Log($"Movement: Horizontal={horizontalMovement} Vertical={verticalMovement}");
transform.Translate(movement * speed * Time.deltaTime);
animator.SetFloat("MoveX", horizontalMovement);
animator.SetFloat("MoveY", verticalMovement);
}
else
{
Debug.Log("Character is idle");
animator.SetFloat("MoveX", 0);
animator.SetFloat("MoveY", 0);
}
}
}
i think the problem actually is it requires a 1 or a 0?
have you tried holding your keys for a longer time or using GetAxisRaw instead
show what you did, and get rid of the movement log as its flooding the console
show the debug log code?
yeah
Debug.Log("Animator Parameters Reset: MoveX=0, MoveY=0");
log the float after you set the float
Like i did with movement?
yeah, but log the animator float
(I really dont like how his console is red even tho its not an error)
just to make sure, what does the code for the log look like
that would be the entire editor probably, just a highlight to tell you your game is running or not
you can make it any colour
Debug.Log($"Animator Parameters: MoveX={horizontalMovement}, MoveY={verticalMovement}");
thats just logging the input, do Debug.Log(animator.GetFloat("X"));
yeah
!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 its what i think, press insert on your keyboard
ty
is he talking ok?
ok so that looks like it should be working?
have you actually setup your animations correctly
if (Physics.Raycast(castPosition, -transform.up, out hit, Mathf.Infinity, terrainLayer))
{
if (hit.collider != null)
{
Vector3 movePosition = transform.position;
movePosition.y = hit.point.y + DistanceGround;
transform.position = movePosition;
Anim.SetBool("isRunning", true);
}
else
{
Anim.SetBool("isRunning", false);
}
}
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
Vector3 moveDirection = new Vector3(x, 0, y);
rb.velocity = moveDirection * speed;
if ( x < 0)
{
sr.flipX = true;
}
else if ( x > 0)
{
sr.flipX = false;
}
Im having some trouble with the Anim.SetBool. I have an empty object which has this script attached. And it lets me move around, the problem i have is that when i move it plays both animations at the same time. There´s 1 Player on top of each other. One that does the Idle and one that Walks. And im not sure what to do 💀 i can share also screenshoots of my animator. I have the transition from Idle to Run with bools.
how would they be incorrects
idk, perhaps you didnt connect them at all or something
you have 2 players? why 2 instead of 1
how do i add movement to my platformer?
you can use a Rigidbody2D to move
then set its .velocity or .AddForce
It´s a long story and funny actually. But if i had to make it short; i have an empty object which has a child object the sprite sheet which the scripts uses as reference.
If i delete the child object everything breaks.
someone?
how can everything break if its just a sprite
the setup should be
player - collider, rigidbody, animator, script...
sprite
other stuff
you can edit messages on discord btw
ik
then it should work idk, record a video showing you playing the game and the animator on the side
thats why im also trying to figure it out
use mp4 or upload to StreamAble or elsewhere
is the Sprite 0011 your player? does this hold the script and animator and stuff?
screenshot the entire inspector of both sprite and toast
well ill have to tomorrow as im getting off bc i got school 😛
bool canMove = !Physics.BoxCast(transform.position, Vector3.one * (playerSize / 3f), moveDir, out RaycastHit hitInfo, Quaternion.identity, playerSize);
This seems to have fixed it
can you dm me or sum
alright
sure you can if you want
alr
if i have a static method enclosed in a namespace do i need the using statement to access it?
As you write it, you have to access it. Namespace => Class => Static, so yes. Either using or full namespace path in that line
hello guys
event isnt invoking what do i do
its null for some reason
i subcribed for it in another script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SelectedCounterScript : MonoBehaviour
{
[SerializeField] private GameObject visualCounter;
[SerializeField] private ClearCounter clearCounter;
private void Start()
{
Player.Instance.OnSelectedCounterChange += Instance_OnSelectedCounterChange;
}
private void Instance_OnSelectedCounterChange(object sender, Player.SelectedCounterChangeEventArgs e)
{
Debug.Log(e.selectedCounter);
if (e.selectedCounter == clearCounter)
{
visualCounter.SetActive(true);
}else
{
visualCounter.SetActive(false);
}
}
}
!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 you call the event before something is subscribed, invoking will result in null errors
You can throw a ? before .Invoke() to check if its null
i did that but it wasnt working without any errors
so i did a null check
that means its not subscribed to by the time that you invoke the event
but how i subscribed in a start function
first thing to check is add a debug to see if Start even runs in that script. maybe its disabled. maybe you also have 2 instances of the player, you only have a static reference to it but theres no guarantee the reference doesnt get overwritten when 2 exist
i just did that it doesnt seem to work
hmm why doesnt start work tho
is the GameObject active?
is the object or script disabled?
does the GameObject have the script attached to it?
How can I do this with slerp or rotateTowards
i dont want it to rotate instantly
i want it to be more gradual
Quaternion.Lerp
yes but... would I do two of them??
How do I combine both of those commands into one line?
I know how to use lerp and slerp, but idk how convey that specific direction I want into a singular slerp command
You create a new rotation with the offset and lerp to it
what am I missing here?
📃 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.
can I not make a transform to store the info?
I want to copy the cam transform, but when I execute the code it seems to be actually altering the orginal cam transgform
https://gdl.space/xivuzekemo.cpp
why is this not setting my tree active
did you just ignore what i told you?
I did fix that part
okay so where are you calling that method
what is BindExternalFunction?
or i guess more specifically, is this delegate being invoked off of the main thread?
its related to ink
that's not a helpful response because idk what that is supposed to mean
ink its used to make dialouges
I used that to kknow the charcter reached the end of convo
okay and are you certain you are calling that method on the object in your scene and not perhaps a prefab or some other object?
you can also try logging some useful info like what you are calling CheckActivation on instead of that super useless "Hyy" log which tells you almost nothing
actually I am calling a prefab beacuse I have a lot of trees I want all of them to appear together
prefabs do not exist in the scene. so tell me how you can tell that isn't working
I dunno what is going on, but that lerp is the EXACT same as writing transform.rotation = camTemp.transform.rotation
1 means return the second value. 0 means the first.
I got function called only not tree grown
So I figured it out... but this solution seems very bad
so the function works just fine and is doing exactly what you told it to
I made cam a Quaternion
and I do this in update
every frame
is there a better way
I can do this
now how do I set these trees active and inactive then
the function is doing exactly what you've told it to do because you are calling it on a prefab which does not exist in the scene and therefore never had its Awake method called
now I removed all the tree I have just this 1
and I updated the code a bit
but this is still not working
Do you get any logs to check, what code is not being executed?
i have a door object with two images for when its closed and when its open, how can i change the sprite of an object in a script attached to a different object
you need to store a reference to the other object and then simply google for how to change the sprite of whatever renderer you are using. Spriterenderer, uiimage or what not.
you mean URP?
The light in 2D version thats all i know
LightweightRP is an older renderpipeline, wonder how you connected this now to the 2D Lights. So what do you need actually? 2d lighting? or the renderpipeline?
2D lighting
Okay, so just to know it. https://docs.unity3d.com/Packages/com.unity.render-pipelines.lightweight@7.3/manual/index.html
And about 2d lighting, you need the universal renderpipeline, and from there, checkout this: https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@7.1/manual/Lights-2D-intro.html
Thx you so much for this quick help
you are welcome 🙂
hi guys, i got a little bit confuse
does create too much text material variants affects apk build size significantly?
thx a lot
explain more about too much text material variants
i often create text material like this when i want custom some new text style
just create new material not the whole font asset
public async Task SavePlayerInfo(IExecutionContext context, IGameApiClient gameApiClient, string key, object value)
{
try
{
Dictionary<string, object> playerData = new Dictionary<string, object>
{
{ "playerName", "Pascal" },
};
_ = await gameApiClient.CloudSaveData.SetProtectedItemAsync(context, context.AccessToken, context.ProjectId,
context.PlayerId, new SetItemBody("playerData", playerData));```
~~I'm getting back an error: Unauthorized
I'm running this on my C# Cloud Code Module on UGS, the docs mention nothing about having to authorize~~
It worked fine with SetItemAsync but SetProtectedItemAsync returns error Unauthorized
What would be the best way to handle seasonal tilemaps? Essentially replacing all the tilemaps and swap it with another spritesheet that's recolored
nvm figured it out, just need to use context.ServiceToken instead
a quick switch way but not design way, would have multiple tilemaps and just enable/disable them
Yeah I thought of that but I wanted to do a good design way like programmatically swapping them
I read somewhere you can do it with shaders? but unfortunately there's no tutorials or anything
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.SwapTile.html maybe this could work
is a TileBase another way to refer to a tileset?
TileBase is the base, TileSet inherits TileBase
I want to make a script that calculates the trajectory of a bullet before firing. I can't find any answer that works for me. I want to calculate where it is going to land giving the initial speed of the bullet and the direction in which it is launched. But I need to be able to get the vector3 from the point where it would fall.
Hello, there's a one milisecond delay when i call the method which sets the attack sword animation trigger
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Attack();
// Check if an enemy is within range, in front of the player, and facing the player
if (IsEnemyInAttackRange() && IsFacingEnemy())
{
// Damage the enemy
DamageEnemy();
}
}
}
void Attack()
{
// Set the "Attack" trigger parameter in the Animator to activate the attack animation
swordAnimator.SetTrigger("Attack");
}
How can i eliminate that?
i think all you can do is to simulate it and find the hit point by physics system
there is no formula to do that, all formulas you can find online doesnt work since they dont know how your "world look like"
its probably due the actual animation setup
you think it's not the code?
I'm sure ChatGPT wrote proper code for you
When in doubt, maybe actually learn writing it yourself
yeah ChatGPT is just overkill at this point, everyone using it and no one learning
it should only be used for actually complex stuff if you need help with it
Maybe keep your opinion to yourself and don't annoy people. I can write this code myself, i used chatGPT to speed things up bcs it was a time sensitive project. I would still have the same problem if i had write the code myself. Just don't patronize people
This is a beginner coding channel. We don't help people that require help with AI generated code because that means you are too lazy to learn it yourself. "Lack of time" is not an excuse.
@topaz mortar stop
pretty sure a 1ms delay is undetectable?
"we"? You can't speak for the entire Unity server. "Lazy" is your subjective opinion. It is "lazy" to automatically assume people who use chatGPT are just lazy.
I don't think an argument is needed here. AI code is very much frowned upon, so don't be surprised if you don't receive any help.
Please be sure to read #📖┃code-of-conduct @cinder spruce , especially about the AI part.
And now back to your issue. I do not think it is a coding issue. Did you check your transition to the state the trigger is enabling? That might just be that delay you are experiencing.
Are you referring to this article? • Don’t post unverified AI-generated responses in questions or answers; check for accuracy, and state what’s AI-generated.
So you can decide to continue discussing the hint on the conduct or just keep going with your issue. Im out for the first one
Okay i don't wanna drag that argument but it says unverified AI generated response which means don't post AI generated code which you don't have any idea what it is. It wasn't the case here
Well, still keeps dragging.
yeah i forgot to uncheck the has exit time box on animation transition. It was fucking stupid, sry for the whole thing
Glad you found the issue. No worries
Hey guys i have a problem with my gameover i think
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
Gameover.ShowGameOverScreen (System.String deathType) (at Assets/Script/Game/Gameover.cs:20)
Death.DeathHandler (System.String deathType) (at Assets/Script/Game/Death.cs:38)
Death.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Script/Game/Death.cs:17)
Can someone help me ?
it says what to do
and what the problem is
I am a very beginner so it's new for me everything
you are trying to use a GameObject that doesnt exist
especially it tells you, it got destroyed. So go backwards from there, check when something gets destroyed, what the last line is your script is firing the error.
I pretty sure that i never destroy it ...
show the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using TMPro;
public class Gameover : MonoBehaviour
{
public GameObject gameOverScreen;
[SerializeField] TextMeshProUGUI timerText;
float timespend = 0;
// Start is called before the first frame update
void Awake()
{
gameOverScreen.SetActive(false);
Death.OnPlayerDeath += ShowGameOverScreen;
}
void ShowGameOverScreen(string deathType)
{
gameOverScreen.SetActive(true);
Time.timeScale = 0f;
}
void Update()
{
timespend += Time.deltaTime;
int minutes = Mathf.FloorToInt(timespend / 60);
int seconds = Mathf.FloorToInt(timespend % 60);
int milliseconds = Mathf.FloorToInt((timespend * 1000) % 1000);
string timeElapsed = string.Format("Temps écoulé : {0}:{1:00}:{2:000}", minutes, seconds, milliseconds);
string totalTime = "1:30:000";
string formattedText = timeElapsed + " / " + totalTime;
timerText.text = formattedText;
if (Input.touchCount > 0)
{
gameOverScreen.SetActive(false);
Time.timeScale = 1f;
}
}
void OnDestroy()
{
gameOverScreen.SetActive(false);
}
}
This is my game over scrypt
whats line 20
gameOverScreen.SetActive(true);
show the Death script
do you know a better way to show my code ?
!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.
do the other script as well
You are registering on an event and never unregister from it
btw you have another, unrelated problem.
If you set timescale to zero in ShowGameOverScreen then Update no longer runs so you cannot then set the timescale back to 1
Yes because i want the user to touch the screen to set the timescale to 1 again
So, if you debug log your gameOverScreen. Is that returning null?
but I told you Update does not run, so how do you think that is going to happen?
cause i have a timer and i want to stop it when the gameoverscreen apear
not if Update is not running it won't
I don't know but i can touch the screen and this is working
because the timescale is not being set to zero due to your missing reference exception
Forget what I just wrote 😄
when timescale is 0 Update does not run
Thats true, but should nt we fix the first problem first? 😄
I'm trying to do it XD
Nah, that was for steve and my wrong assumption of update. But yeh, back to your issue. Can you please debug log your gameOverScreen above line 20?
The name 'gameoverScreen' does not exist in the current context
yeah... brain.Start(); please
check your spelling
and !vs just to be safe 😉
!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)
Also can you screenshot your hierarchy showing the object with the Gameover script
what is it ?
so which object is the GameOver script on?
gameoverScreen or gameOverScreen?
thats why I posted the tutorial on how to setup visual studio, if your ide did not autocomplete it for you
Canvas
Ok, I see Gameover has an OnDestroy method, which means if it is Destroyed then all of it's children are Destroyed as well
Do i need to unregister from the event ?
yep, you always should in OnDisable and register with OnEnable. Imagine you register to the event and destroy that script/Gameobject that has been registered. That will result in a missing reference inside your events subscriber list
Say, you have the 1st class, which calls the event, and 2nd one, which subscribes to it.
If the 2nd class lives longer than the 1st one, you'll definitely have to unsubscribe it from the 1st class' event, for the 1st class not to call the event for the 2nd one, which has already been destroyed.
If the 1st class lives longer than the 2nd one, you don't necessarily have to unsubscribe the event, but it's usually a better practice.
And the subscription and unsubscription are usualy done in the OnEnable and OnDisable methods respectively
i'll try this
how 2 make dragging for 3d object? (i need constant y & it's already known)
look at the IPointer interfaces
what do i need 2 import?
well if you googled Unity IPointer, then read the documentation, you would know
ok, i readed all the docs about it & idu what difference between OnPointer methods & OnMouse methods?
iirc OnMouse methods do not work with 3D objects, IPointer interfaces do
they work, i all project made with it
yep, mouse methods work with the collider
wait OnMouse only works with triggers
idk, i know only what OnMouse doesn't work with objects on canvas
even with colliders (yes, i really added collider 2 it)
Is there any way I can run a function when a Serializable Public Variable's value is changed? For example, if I have a float tat goes from 0 to 1 and has a slider in the inspector, the moment I change the value of the float in the inspector, I want to assign that value to another variable in another script.
maybe float value {get; set;}?
Ohh I forgot that existed
I also saw something called OnValidate() will that work too?
idk what is OnValidate()
may work
Yeah will try that instead as get and set just makes the code longer
Yeah it worked perfectly, thank god.
good lord , im stuck here , so im saving and loading the saved data but i wanna set lets say the player position to the saved player position or player health to the saved player health but im not sure how i can do that without using references since my SaveAndLoadingSystem script is a singleton and there is the Load method which is when i wanna set the health or player position to the saved data ones and im not sure how to do it without needing references
it's not beginner, but you can save in files & load by regular expressions
i do save in a json file but wdym load by regular expressions?
for example, i making chess & in file i have moves for figures
& i load it by foreach(Match i in Regex.Matches(fileInString, "pattern")
impossible
you must reference the player object to change it value (idk how to change the data of some objects that you have no idea where they are) but your save and load system can use the existing player reference in other object eg game manager
& i checking what is this move type, coded in letter, directionX, directionY coded by ints (int.Parse("120") = 120), & type of move coded by symbol or 2
about situations where you know where is a symbols in string from 1 of edges, you can just i[index]
{
var playerData = await CloudSaveService.Instance.Data.Player.LoadAsync(new HashSet<string> { "playerData" }, new LoadOptions(new ProtectedReadAccessClassOptions()));
Unity.Services.CloudSave.Models.Item testItem = playerData["playerData"];
Debug.Log(testItem);
Debug.Log(testItem.Key);
Debug.Log(testItem.Value);
}```
testItem.Value is Unity.Services.CloudSave.Internal.Http.JsonObject
How do I access or deserialize that? Or whatever I'm supposed to do with this to get my stored value?
I've been going through the docs for two days, but can't figure it out.
Here i have this code, it's for a Monster AI which walks blindly when not hearing anything, but chases the loudest audio source once it's too loud: https://pastebin.com/TW4xtbgu
The problem is that when the loudestSource is changing position (for an example: it's a player), the script doesn't update loudestSource position, so the agent is going to the last known position of the loudestSource, and then it just stays here, waiting for the player to stop making noise, so it return to the Roaming state.
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.
Is the sound source not moving with the player?
it IS the player.
oh wait, i think i know why it doesnt work.
Hey there people! can anyone help me try to understand how to add multiple jumps in my 2d player script?
basically i have this script with jumpbuffering and coyote time set and working fine, but i really can't think of a way to add multiple jumps with all these, i've tried implementing it but with poor results, does anyone have some advice?
it works now
Have a jump count int variable. Add to it every time a jump happens and reset it when the character is grounded. Then check it before jumping.
Ah, I see you have something similar with remainingJumps. Is it not working?
Also, share the !code properly.
📃 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 did so but it really does not work i can't really think of where to place the check in my script, i have a variable remaining jumps but it's not working where i placed it
i shared it sorry forgot i could send it that way haha
yeah it's not working i don't really know where to put the check tbh
This is a very unreliable way to implement jumping. The logic in update might run several times between fixed updates, you know?
Start with understanding why it's not working.
Use debug logs or the debugger to debug important information to understand what's going on
yeah this is a project i started to learn making 2d platforming movement so it's a mess haha
chung
How can I rotate the security camera that it faces into the right direction?
I thought about using the normal vector, but I don't know how to implement it.
I use a raycast for the position
Hi can someone help me it's a problem with no f*cking reason to happen, juste two GO that i can't use SetActive() on them for no reason
what is "the right direction"?
i was thinking maybe completely removing jumpBuffering as it's pretty much a form of "extra jump" but im not sure
What do you mean you can't use SetActive? What happens when you try?
you'd have to show the gizmos for the object's local axes
so we know which way the mesh is facing
Nothing really nothing, the Debug.Log is working but the other code is not read or idk i give a part of the code here
if i can
Yes you should share your code and how things are set up in the scene and inspector
but likely either your code isn't running, or you are referencing the wrong objects
Do you mean this?
yes
float direction = moveScript.moveDirection;
GameObject sideToActivate = (direction > 0) ? rightSide : leftSide;
if (sideToActivate != null && isAttacking == true)
{
rightSide.SetActive(sideToActivate == rightSide);
leftSide.SetActive(sideToActivate == leftSide);
if (sideToActivate == rightSide)
{
glowAttackEffectright.SetActive(true);
Debug.Log("glowAttackEffectRight");
}
else
{
glowAttackEffectright.SetActive(false);
Debug.Log("PKSASEDESACTIVEPTN");
}
if (sideToActivate == leftSide)
{
glowAttackEffectleft.SetActive(true);
}
else
{
glowAttackEffectleft.SetActive(false);
}
}```
make sure your tool handle rotation is set to local though
but if that's the case then you basically want:
camera.transform.rotation = Quaternion.LookRotation(surfaceNormal, Vector3.up);```
The effectsglow aren't working but the rightSide and left are working
show the whole script, ideally in a paste site. Is this happening in Update? Looks to me like you're calling SetActive(false) a lot as well
Debug.Log around each SetActive call would help
Perfect worked 🙂
I don't remember how to use the paste site
I do
just copy your code into one. Hit save. Share the link
But it's not help me
show it
How is select which camera is selected at startup?
What do you mean by "selected"?
When I have 2 cameras in a scene, when the game is started which camera is on the screen
They are both going to be drawn
The order in which they're drawn is determined by their depth
Is there an UI element that shows the depth
Thx
yo is there a way to like make dictionaries in inspector? like i want to make messages in ui, i don't want to make 5 scroll views and want to make it procedural, i could make an array of string but i'd have to add either "Me: " or "[User's name]: " to each message and i could misspell something so i want to make like a dropdown to choose a user and a message they sent, is there a way to do it?
i think there was something like that in line renderer?
yea, sum like that but with enum and string
Or just serialize a list of a custom struct
and load into a dict in Awake
like a script struct?
There's only one kind of struct
ohhh
how do i have transform.lookat not apply to upward and downward rotation
make it look at a position that's at the same height as you
Vector3 lookTarget = whatever;
lookTarget.y = transform.position.y;
transform.LookAt(lookTarget);```
e.g.^
public enum User {
Me, TestUser
}
public struct Message {
public User user;
public string message;
public Message(User user, string message) {
this.user = user;
this.message = message;
}
}
public List<Message> messages;
``` like this?
Yes but get rid of the constructor and you need to mark the struct with [Serializable]
okay it shows up in the inspector, thanks
hello! I'm trying to make a 3D platform system for my player (I'm using a character controller) and I do not know how do I handle the collision between the player and the platform, I tried parenting the player to the platform and unparenting it when he jumps off, which work's fine if the platform only moves in horizontal axis, but vertical movement is still very janky whenever the platform moves faster than the player can jump
Any tips or good practices that I should be doing?
also whenver the player is on a platform and a different platform hits the player it just goes through him, which is an issue
guys. how do I make it so when pressing shift my player runs and the run animation plays and when letting go the run animation stops? right now when I let go of shift my player still runs
Hello everyone, I have a question. I'm almost done with my game, but can I find the game registration, login and settings parts in Unity Asset or should I prepare it myself? If there is an asset you know and it is good, that would be great. I would finish the game at least 2-3 days early.
}```cs
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift) || KoşmaButon.KarakterKoşuyor)
{
inputMagnitude *= 2;
inputMagnitude2 *= 2;
}
There is a bunch of solutions to that and (as always...) it depends on your implementation and gameplay goals, I suggest checking out some YouTube tutorials on "moving platforms" in Unity. I personally haven't had this problem when developing because I was using physics-based movement (HexaBody)
Do you use getkey?
I looked over a bunch of stuff, but I can't find many 3D resources
I use blend tree
https://forum.unity.com/threads/player-stick-to-moving-platform-two-ways-solution.345086/
Here are 2 example solutions
Just Google it, there is about 10 YouTube tutorials and multiple forum and reddit posts with solutions
And it also depends on how you move your player, for example, when jumping off, you should add velocity of the platform to your player because that's how physics work
is there a name for when you put an if bool == true in your if statement and then put bool = false within the if statement
to make it only occur once
a ternary ?
Not that I know of
idk what u mean
code always only occurs once
unless you put it in a loop