#💻┃code-beginner
1 messages · Page 820 of 1
guys, who knows how to stop the stack's flow for some time. like, the analog on time.sleep() in python but for unity? Thread.Sleep doesn't work for me idk why
Why
Design your level in a way that doesn’t make this happen
well, there are some actions i need to do but one should go after previous one
don't try to make the thread sleep, that'll just freeze everything. use timers or coroutines (or their alternatives)
ohdamn
(timers here referring to having a variable that counts time, not the class called Timer)
are you referring to ide configuration
Yep
The one that i some how got it to work very bad
do you have proper syntax highlighting, and do you have autocomplete
1 what and 2 no
syntax highlighting = pretty colours on your code
I have some kind
Let me look
I jave blue green blue pink
And some other colore idk how to name
And ys is outo fills but idk if is the good comand
If type names, fields and functions appear as you type code then its working
also if errors are underlined
show them
public class Singleton:MonoBehavior
{
public static Singleton singleton;
}
```is this not how you make a singleton?
i guess i will just do that for now .
you have to assign your object to the field you created
this is intellicode, not intellisense
Probably Copilot. Intellicode is a lot more tame afaik.
is intellicode not the name of the feature within copilot?
i thought copilot encompassed a lot more
well, i guess now it's "inline suggest" according to the setting names, but that's much vaguer...
They are killing intellicode
the product or the feature
Former, it’s copilot now
is there a way to do it in engine or do i need to do it in code
with limited rates
well the feature dosent work xd
doesn't "copilot" include chat and terminal integration and such
Most people do it in awake or in a property, google has examples
They mold copilot like play dough to fit wherever it can in order to increase the amount of users using copilot
It is an earlier feature to handle predictable edits, like repeated renames and other small stuff like that. Also reorders your intellisense suggestions.
shud i reintall video code editor?
sorry.
are you on windows or mac
(It’s also in Notepad and Paint btw 😭)
windows
hm i don't remember what the bind to trigger intellisense is on windows.. probably ctrl+space or ctrl+period
what does it even do in paint
Image prompting i think
you mean the panel whit suggestions of comands?
if yes is ctrl and space
well they aren't commands
scrip or code?
if they're showing proper identifiers or keywords, rather than just words in the file, then it's configured properly
perhaps show that window
what im talking abt is this window or pop up or how ev you wana call it x3
so i just need to olwos press ctrl space?
oke ty tho im not doing now cus ehhh...
i dont feel like codeind rn sorry
you shouldn't have to, it should show up when you start typing an identifier automatically
yes and no
1 sec il show you
frist pic is automatic and second is when i press it
btw sorry for so meny pics i just cant type well in english
how to initiate a function inside a command? Can i do smth like Tween.onComplete( void smth {blablabla});
so the same thing?
it's working normally then
use a lambda (local methods or just method references would also work)
not ryly it give diverent comands i mean
those are the same lists
just to be sure it works it hase to be void OnTriggerEnter(Collider other)
yes?
ik tho till i learn how to code idk what to do yk?
You wont learn any better with using AI
People have been learning to code the old fashioned way for over 40 years now, people pretend like its suddenly impossible without AI
I cant decide. I have class which stores dictionary( SO and id). Where should i make id? in dictionary class or ScriptableObject?
i just sed that till i learn how to code what you want me to do
read lol
coding cant be learned by watching long tutorial videos or using AI
Reread what i said, and what you said previously
then how i learn it
Code, read documents and ask questions in experienced programmers chat groups
im broke to get courses
I think paid courses are scam. there are courses for free
code what i have 0 expiriense
Guys what you think? I think its better to make in Dictionary
Code very simple arcade games
What do you mean with "where should i make id"?
Like where to declare the type or?
Plenty of cheap or free ones
i have no money TvT
I had maybe small experience, but you could say i had 0. Then started doing these steps.
- What i want to make?
- How much time will it take? Triple time
- Start coding
- fix or look up examples if something doesnt work
Something free seldom requires money
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Triple time seems a bit inaccurate
Maybe cubing time would be better XD
referencing SO in files, like levels or items. Thats why made class with dictionary, which has SO reference and id. Before that class i generated id in SO, but maybe i should do it in Dictionary
everyone had 0 experience once
that would be using the id, wouldn't it
are you asking whether to store the id in the SO or not?
im doing the tutorials...
yes
ye but i will strugal more then you think to learn to code
you should probably store the id in the SO, to have a reverse mapping.
thus, you should probably make the id in the SO
Dont we all struggle when starting something new?
Yeah sounds like the SO should own the ID
i have a very low bar based on past experience with arrogant, entitled beginners.
you're only 1 of those 3 qualifiers
Okay, then OnValidate im going to pull ID and store in dictionary
Another day, another bug. Goodmorning people
i feel like Reset or Awake would be adequate, depending on the lifetime of the dictionary in question
ye but idk if the tutorial from unity will ryly help me learn how to code idk...
Doesnt it get called, when data is added in inspector?
stop doubting and start trying
if it doesn't work out, there are other tutorials for you to try
but you won't learn at all if you never start
yeah, so why do you need to refresh the ID every time the SO is changed
It gets called in a bunch of places
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/MonoBehaviour.OnValidate.html
OnValidate is called at various stages during the Editor's normal operation, such as loading scenes, building a Player, and entering Play mode.
OnValidate can be called often when the user interacts with an Inspector in the Editor. It can also be called from threads other than Unity's main thread, such as the loading thread. For these reasons, only use OnValidate to validate the data that changed. Don't use it to do other tasks such as creating objects or calling other non-thread-safe Unity API.
You also don't learn by copy-pasting tutorial code. Gotta play with it, see when/why it works, read about it. Try to use it in different ways.
OnValidate of the SO or of the dictionary class?
wanted easy way to add ID in dictionary, when putting SO in dictionary
(If i understand correctly you have some dictionary wrapper class?)
Or where is the dictionary stored
there are other messages that seem more appropriate for that
public class SO_Dictionary : ScriptableObject
{
[SerializedDictionary("ID", "ScriptableObject")]
public SerializedDictionary<int, ScriptableObject> db;
void OnValidate()
{
}
}```
this doesn't really make sense. you want an easy way to add the SO, when you add the SO?
you can't put the SO in without a key
starting to feel like this is an x/y problem
I made it as SO, because it will be reused for other SO. Maybe i should add Interface for id SO
what's the overall goal here?
Easy to get SO reference, when loading data from json file
yesterday i asked and got answer, that dictionary would be best option for it
and you want to add serializedobjects to the dictionary in the editor?
i'm not sure a serializeddictionary is the best flow for that
you could just have an array/list to add to, and then build the dictionary in memory
having the id serialized in 2 places seems like a potential spot for mistakes, just accidentally changing the ID or something like that
I needed way to add object to it, thats why took Serializeddictionary, which doesnt make big difference
and you wouldn't want to have to constantly refresh the serializeddictionary
which doesn't make a big difference from what
performance
Thats why, asked make id in SO (Harder to get reference, when you only know id) or dictionary (this would work more like database from which classes can take reference)?
So all i do when codeing is trying and hopeing it works and then if it dosent i seek help?
ok, that's not what i'm talking about
you can do both. that's what a reverse mapping is
same as with AI, but you think and later wont make same mistake
not all trial and error. gotta read up beforehand so you have a good idea of what you're going for first, and then try with that knowledge
why?
I can berly understand english idk if i can learn codeing from reading
why what? the error seems pretty clear
what's your native language
what's wrong here?
the font
presumably you did not assign an AudioClip to the AudioSource, and you aren't providing an AudioSource there, so it doesn't know what you want it to play
also probably this ^
Romanian
hahaha funny one
yes
ok
Is butt the component this adiosource attached to and how is the function being called?
Debug.log is a good idea, see if the function is even being ran.
ye id reccomend adding debug log as well
then try googling for romanian c# resources
yes
np
btw, there is a small delay before playing the sound. how to fix it?
There is none
The delay is likely due to your SoundClip having blank space (* the clip/audio file may have an amount of time prior to the desired sound/noise.)
i googled and found 2
no, it isn't
I'd say using something like chatGPT would be a good resource for you. But it sucks not knowing english, english is my 4th language and man am i glad to know it, resources in other languages are hard
As in, no sound for the first second prior
if you're romanian, learning french would be easier imo
that wasn't mentioned...
ah i missed the singular message that mentioned that. mb
I think I misunderstand something... they mentioned a delay, the first thing my mind goes to is the audioclip (soundclip is the wrong term) having no ("blank") sound for x time
Reverse mapping is hard to understand. Its about making one object from different object?
you have 2 things, id and SO
from id, you can get SO (forward mapping)
from SO, you can also get id (reverse mapping)
Part about doing both? in the end i should create id on SO and then add to dictionary
No
yes, that's what i said to begin with
and you can build the forward mapping dynamically, so it isn't serialized (where you can accidentally mess it up)
guys, please. how to remove the delay in playing sounds in unity? there is no delays in my sound
that's why i said to consider a list/array instead
If it's not an issue with your audioclip, i'd point to the script / function triggering the sound.
what's the issue then?
How should we know without seeing it
Hard to say without seeing
I wana learn to code not just make somting stupid and not learn enything
!code
Just start to the best of ur ability and google whatever issues ur facing and if u cant find/understand something ask here for help
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
@solar hill @queen vale
Its gotta be at the start of the message 
Is it a large audio file?
very large
62 Kb
gpt and LLMs are just tools, if youre trying to build a project with them, you'll end up with slop. But, if you use it to get some information on how certain scripts work, it can be very useful. Find english tutorials, look at the github repo, ask GPT to explain the code in your language. Its a very feasible way to learn
in serialize i cant mess it up, because using it only for referencing SO. I could make serialized array, which on game starts add them in dictionary, without allowing to change id
Ye but im scared when il try to code lets sey my own game like just somting simpel and i cant figure it out at all im eberesed ro ask every time or sum yk?..
Chatgpt will spit out wrong information confidently
use deepseek instead
Keep a simple "scope". Watch tutorials. Each piece builds the puzzle.
Fear only keeps you from learning
Do collab work, if you are that scared, but thenn nnot100% copy paste AI code. it only messes up project
Can you explain abit more pls?
when it's a serialized dictionary, you could accidentally break the forward mapping.
Gonna go on a whim and say it might be related to your scene manager loading, if its doing anything async it might cause lag that delays the audio
As long as u follow the guide on how to ask for help ull be fine
Trust me half the times i ask for help here i realize its something really simple and kick myself
"Scope" refers to... the grand idea of your project, how much is involved to create the final project... and MMORPG, has a TON of things going into it... a match 3 puzzle game is much more simple compared to that.
The man who asks a question is a fool for a minute, the man who does not ask is a fool for life.
I know, because of changing id,
but i wont touch id. it will be pulled from referenced SO. i think 100% fool proof
if you don't know how to code and there arent a lot of resources in your language, asking it to explain simple tutorial scripts is probably something it can handle. I understand LLMs can spit out wrong information, but if he doesn't know english very well, it could be a very good resource imo
Great thing about coding is that theres almost always resources in every language
but honestly, your english is good enough to ask for advice
are there many tutorials available with subtitles for romanian ?
because youtube's auto trancription thing is getting quite good as well
Im shy to come for every problem il encounter yk?..
do you know what "accidentally" means
When world stopped using machine learning and chat bots, and started to use word AI for everything that isnt AI
Like most internet chatrooms, anonimity is pretty common
What exactly is there to be shy about
We dont know you
You dont know us
i know. it means there's atleast 1% chance to make mistake
I'm dumb, I give wrong answers all the time. people correct me. No biggie.
Noones gonna hate you for asking a question
I just have a trauma whit that is all..
so use the method where you can't accidentally change the id
Just gotta bang your head on the wall long enough to find the answer
Cascadeur renaming their briliant automatic interpolation to "AI interpolation" as marketing... even though its just an advanced ML algorithm 
Srill i fell like someone will sey why i keep coming back or sum like that every time or etc.
kuzmo comes back every day
option i said before. use array to serialize objects and OnAwake for each object take id and story it in dictionary, which wont be serialized
many of the people here, active right now, ask questions frequently. it's how learning works
...that's what i said, yes
Look at my prof. been here 5 years. Doubt most people even recognise me (though tbf, i dip for months sometimes).
So many products say AI, but in end of day, its one if else statment
-# 5 years ago was 2017, right...?
Like i have already accepted that i know nothing and any question i ask will probably be stupid so if im gonna be stupid might as well ask people for help sooner than later
2021 was a year ago wdym
.... it's 2026, 2026-5 = 2021..?
No?
-# i thought that was 2015.....
damn, no gifs in this server ? 
Was a jest
-# it was a joke, yall
i had such a good gif for this
Oh ok i started to feel old
mannn.. had me questioning my math
Fair though
Idk man it still feels like 2020 to me
Scriptable object doesnt have on start or on awake
Well uhh il try tomarow cus today i feel burned out sorry :<
nothing has OnAwake
it's not called that lol
using System.Collections.Generic;
[CreateAssetMenu(fileName = "Dictionary", menuName = "Scriptable Objects/Dictionary")]
public class SO_Dictionary : ScriptableObject
{
[SerializeField] public IdObject[] SOs;
public Dictionary<int, IdObject> db {get; private set;}
void OnEnable()
{
db = new(); // now its created
foreach(IdObject SO in SOs)
{
db.Add(SO.id,SO);
}
}
}```how this?
ooo i forgot about building the actual dict. docs say to use OnEnable instead of Awake so it'd build when you enter playmode
forgot that now i have issue that cant access LevelData (SO, which is IdObject), because Dictionary reference IdObject
you could have separate SOs for different types maybe, depending on what you need it to be able to hold overall
(though why can't you just reference SOs directly again?)
idk, im dumb. I could just add this logic in my static class
because ill have different SOs which need id
can you reference SO in Json? XD
cool, that answers my question
what are you using them for ?
if you want to implement like a game save, you can serialize and deserialize them
level progression. To track what levels are unlocked and how they preformed in each level
you can have the monobehaviour write to its data
have a field like playtime
for instance
setPlaytime(int something) on the moniobehaviour
writes to the data
give documentation
i did this a while back
let me see if i can get the scripts for you
okay here's an example
i have something like
public class BlockData : ScriptableObject
{
public string blockName = "Block";
public bool isImmovable = false;
public GameObject blockPrefab;
public Vector3 BlockPosition;
public enum BlockColor
{
White,
Red,
Yellow,
Blue,
Purple,
Orange,
Green,
Black
}
public BlockColor blockColor = BlockColor.Red;
public List<BlockColor> containedColors = new List<BlockColor>();
and in a monobehaviour, i can access position to move it at the start of the game:
if (runtimeData != null)
{
_gridMover.gridPosition = new Vector2Int((int)runtimeData.BlockPosition.x, (int)runtimeData.BlockPosition.z);
}
else if (data != null)
{
_gridMover.gridPosition = new Vector2Int((int)data.BlockPosition.x, (int)data.BlockPosition.z);
}
or i can write to the data like this:
runtimeData.containedColors = new List<BlockData.BlockColor>(_containedPrimaryColors);
Is it good practice to edit scriptable Object fields? Also it won't save between sessions
do you mean changing them at runtime
Very big example xD. You can make example about it in 5 lines
I talked about saving data between sessions and he popped in and gave runtime data saving
you asked if it is good practise to edit scriptable object fields, didn´t you
Had question until googled and got answer, that SO set values don't get saved between sessions
then you should ask google more often
depends if it's during runtime or in the editor . . .
In editor changes persist!!!
Okay, it's with everything in editor
In a build changes are not kept so this cannot be used to "store" data long term
That's why using json
Then just be aware of what happens if you modify a scriptable object asset
Best to avoid it during runtime/playmode
with a game build, editing an SO will not store the changes made, but inside of the editor, changing an SO field will KEEP any change made . . .
And it will only get saved in the editor if it gets marked dirty somehow
its an example from a game with a functioning save system that i made
just store it as json
im setting fields on an instance of it
which can be serialized and saved to json
its just cleaner to have a runtime data copy and save those changes to the data of the object on session quit
/ session save
So you save in SO and then on quite you save it as json?
Sounds like you need 2 classes
Or to make a new instance at runtime to avoid messing up an asset
At that point, can't u use static class. Also, some stuff you can turn into json
wtf is that?
hmm, no other errors in the console (there's only one red 🛑 message)
what version?
Does anyone know how to use material property blocks for material switches?
My print value is updating properly, but the material isnt changing when I adjust my blink variable (it does for the others though)
which makes me think the reference is wrong or something else
a switch should be a true/false boolean, and an int should work as 0 and 1 for that, no?
You can't change keywords with a material property block
_TESTCOL_ON sure sounds like a keyword here
Changing keywords means you're loading a totally different shader variant
I'm not sure if I am following, where did I change keywords?
This is the property list
the switch says it's using _TESTCOL_ON
Hmm let me try something then
I know that Unity can toggle keywords based on material properties
your setup looks like you're meaning to use [Toggle]
(i have no idea how this interacts with Amplify)
the [Toggle(FOO)] material property drawer causes unity to turn on a keyword named FOO_ON if you set the property to true
Yea I took off the keyword name
so it should just be _TESTCOL
unfortunately its not working still
hey guys I have a weird problem that im not sure is fixable but ill ask.
I have a pistol
I shoot 3 times and each time I look more to the left
the probem is one of the shots are to the right.
I have a drawray for my raycast and when I look slightly to the left it sometimes bounces to the right.
is this a unity bug or fixable?
Oh shit
we would need to actually see your code to know what is happening
so is that why I cannot fetch the property with PropertyToID?
because the keyword is changing?
Your actual property name is _TESTCOL, and that should have been fine
I think the problem is just that a MaterialPropertyBlock cannot cause keywords to change
So if you had directly set the int on the material itself, you'd have seen it working
Which isn't ideal in my case, I would need to do a property block :<
I would suggest replacing the Static Switch node with an If node
check if the _TESTCOL property equals 1
Keywords are appropriate for enabling or disabling large, expensive features
So switchs arent ideal in my case
yeah, Static Switch would be useful for turning on a major feature
there is +999 but collapsed
oh yeah, just not any other messages
These messages get spammed when Unity is failing to free up some memory that it allocated
Sometimes that comes along with an error that prevented it from doing that
what should i do there is about 2gig left in the task manger
so tell me again, what behavior is happening, and what is the expected behaviour
Im going to try an If node real quick
Try upgrading to the latest version
its the latest lts vir
can you not
every time someone told you to stop shitposting you apologize and then continue to do it
there si no right channel for that
nice (:
I wasnt aware Switch wasn't the play here
oh yeah ididnt know they updated it thx
in plain shader code, you'd see something like this:
#if FEATURE_ON
// do something
#else
// do something else
#endif
The keyword affects which block of code gets compiled in the first place
When I look slow left and shoot like 5 times. some of the shots are to the right
vs. a dynamic branch, which would be more like
if (_UseFeature)
// foo
else
// bar
both sides of the branch are compiled here, and the side you take depends on the property
how my shots are going
do you have a video?
Yay! It works perfectly, thank you ❤️
For some reason when I try to Instantiate an object it spawns multiple objects instead of just one. Here is my code: ```using System.Collections;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Pool;
public class PotionSpawner : MonoBehaviour
{
public GameObject[] Potions;
public Transform Player;
private void Update()
{
StartCoroutine(SpawnPotions());
}
IEnumerator SpawnPotions()
{
if (Input.GetKey(KeyCode.Escape))
{
// Spawn Potions around Player
Instantiate(Potions[Random.Range(0, 2)], Player.position, Player.rotation);
yield return new WaitForSeconds(5);
}
}
}
You're doing it every frame
because it's in Update
oh ok
As for your coroutine usage - it is pointless in your example
So I should change the If statement to update
the fact you are doing this in a coroutine does nothing
other than adding complexity to the code
you are starting a new coroutine every single frame here
The coroutine is for later
and then the coroutine immediately spawns something (if the key is pressed) and then contiunues to wait pointlessly for 5 seconds before it stops existing
I can't give you any advice on what to change unless you explain exactly how you want the code to behave
it's basically already in Update
Can you explain how you want this to work?
Do you want to spawn one object every time the player presses Escape?
if so:
void Update() {
if (Input.GetKeyDown(KeyCode.Escape)) {
Instantiate(...);
}
}```
The goal of the code is to spawn an object every couple seconds, but I currently have it set to escape in order to spawn the items whenever
Otherwise I would have put it in a while loop
Currently the latter but I would like to get it to work inside the coroutine for the future
For the latter I gave the example above
for the former you would do something like:
float timer = 0; // a timer variable to keep track of how much time has passed
float interval = 5; // time between spawns
void Update() {
timer += Time.deltaTime;
if (timer >= interval) {
timer -= interval;
Instantiate(...);
}
}```
ok thank you
I wouldn't recommend a coroutine here, as it's more difficult to make a consistent/accurate timer with one
it's also a bit more complex, for little benefit
i also tried lerp and timedelta but the raycast keeping bouncing the wrong way im turning. the smoothing doesnt change it from bouncing the wrong way im a little lost
anyone got a really good 3d character controller?
idk if it matters but i want to be able to change the gravity for the player
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
this is pretty easy in most if not all controllers
try googling around
^ this is exactly what i do
you shouldn't be saving directly to it
always an instance of it
even better if you make a runtime copy and edit that
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PocketPath : MonoBehaviour {
private void Update() {
// Ray ray = cam.ScreenPointToRay(Input.mousePosition);
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f));
float maxDistance = 200f;
//Red ray in center
Debug.DrawRay(ray.origin, ray.direction * maxDistance, Color.yellow);
}
}
This smells like an order-of-execution problem
I bet the raycast is being computed before the camera rotates
this will make it look like the raycast is angling slightly away from wherever you're trying to aim
interesting I havent thought of that
i get what your sayin but im havin a hard time figuring out what I need to change or add
was reading the unity documentation looking for some explanation on a certain thingy but couldnt find much on it, or the documentation was just too hard for me to read at the moment
im working with button inputs and an input reader right now and im wondering where i could find some information on what the rest of the actions following context. could do
i see canceled, interaction, and i was told to do performed, but im wondering what others might do, as i feel they could probably be very useful
like i see one called time and i wonder if that has a count based on deltatime (if inserted)?
unity documentation kinda confuses me
Have you considered looking at the docs?
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.19/api/UnityEngine.InputSystem.InputAction.html
It explains what everything does
what part are you confused by
i used the search bar and it probably gave me 100+ things i did not know how to sort out which was which
Oh sorry I realized you're looking at CallbackContext. Which is here:
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.19/api/UnityEngine.InputSystem.InputAction.CallbackContext.html
And here's an explanation of what time is: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.19/api/UnityEngine.InputSystem.InputAction.CallbackContext.html#UnityEngine_InputSystem_InputAction_CallbackContext_time
thanks!
Well you would click on the thing that you're actually interested in knowing about. For example if you searched CallbackContext the first result is the article for the CallbackContext struct itself.
The rest of the results in this case are just other pages that reference it.
read the title of the link to understand what page it will take you to
I tried lateupdate but that didnt work
any tips on how id go about it ?
how to get addressables label of this current gameobject that has the label c#
store the label at the time you initially retrieve the object, then you just get it from where ever you stored it
For some reason instantiate is spawning multiple copies of the same object. How do I get it to only spawn one copy. Here is my code: ```using System.Collections;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Pool;
public class PotionSpawner : MonoBehaviour
{
public GameObject[] Potions;
public Transform Player;
private void Update()
{
if (Input.GetKey(KeyCode.Escape))
{
// Spawn Potions around Player
Instantiate(Potions[Random.Range(0, 2)], new Vector3(Player.position.x + Random.Range(-5, 2), 0, Player.position.z + Random.Range(-5,2 )), Player.rotation);
}
}
}
GetKey is true for every single frame that the key is down, perhaps you want a method that only returns true the first frame the key is pressed
Yes that would be what I am looking for
then consider looking at the documentation
I changed it to GetKeyDown and it worked perfectly thank you
where do i start if im trying to learn how to make a 3d game in unity? (i tried googling for the answer but i dont really know what to look up)
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
huh i dont know how i didnt see that
do u mean i gotta type it out initially?
i'm saying that where ever you initially load the asset via addressables is where you store the label in a variable because surely you're loading it via addressables and not just trying to reverse engineer an addressable label from something not loaded via addressables
well in my case im tryna make a levelId string variable that structures like this:
<addressable label>#<level number>. So for convinience sake i dont want my future self to type of the addressable label that this obj has, i want it to retrieve via OnValidate()
or by naughtyattribute's button to do so.
so i kinda do need to reverse enginner
since this sounds like something you're doing purely in the editor it will actually be possible to do, it'll probably require using things from the UnityEditor namespace (which means you'll need to make sure to exclude that code from the build), but you can use the AssetDatabase to get an asset's guid from its asset path (which you can also get via the AssetDatabase), then with the guid it looks like you can call GetAssetEntry on your AddressableAssetSettings object to get the entry which will have the labels assigned to that object
Question:
I'm pretty new to Unity and i'm wondering how I would make some code that isn't linked to scripts attached to game objects?
I'm used to using Blazor and ASP.NET for personal projects, so trying to find the unity equivalent of making services/models/di/singletons/etc that aren't in game objects.
just don't inherit from monobehavior
you may also want to consider SOs or singleton monobehaviours, depending on the specific needs of the task
so any services/models/etc i want to make just get thrown into the asset folder without any exceptions? Wouldnt anything i want running or saving info in the background still be reliant on gameobjects?
well, if we want to think of singletons it's probably a static class versus monoclass versus scriptableobject
in the end its c#, make them static and access from anywhere. dont make them static, create an instance on runtime, whatever you like. GameObjecsts are just visual representations with properties that are still c# classes in the end. monobehaviour just brings the unity engine loop conveniently to your scripts
static -> allocates when first called
mono -> exists on scene and may not exist when first called
scriptableobject -> doesnt exist in scene but is allocated similar to how resources are loaded
mono singleton is interesting such that it can serve as an entry point for each scene, meaning that each time you load a new scene that singleton can be a completely different instance.
i find that monobehavior singleton in an additive, persistent scene makes more sense and is easier to manage than having the singleton in every scene
yeah there's a lot of ways to use them. Additive is useful for something like a object pool where you only ever want to allocate objects once throughout the game
i am slowly leaning towards scriptableobject singletons lowkey
how i understand, i cant serialize field in static class to reference SO?
static means it’s associated to the class, not a instance of the class
So no inspector correct
how i can get reference of SO in static
Generally you don't want something to be static, you may want to look into the singleton pattern
Noones gonna read a one liner log...
never?
static can be used for methods that cover specific outputs for example. I use static methods for easing, that just output an eased value based on the start, end and progress time. But trying to access a "runtime" object reference from a static class is the wrong direction. You rather have, as vertx says, a singleton handling your reference and you couldhave a static class that extends your methods like with my easing example.
I mean it’s not necessarily the wrong direction, just depends on why they wanted it to be static
if you try to access a runtime object from a static class, that lives outside of your scene scope (in unity), you will most likely run into a hard coded reference to either a name, a file to be loaded by name/path or something else. I mean, sure, you CAN do that, but I would avoid it.
I hope, im not only beginner, who thought that all games need GameManager
Most do yeah
Dont see reason for my game to have. mostly it stores game states and sessionData
managers are a good concept to keep your things organised. Most likely having a manager for specific systems and one for your main game loop for example. Otherwise you could run into lose code that rely on each other but you lose the overview of the states they are in, because all scripts should in theory cover all states at all time.
thats great, you can master anything. if you cant coding try to get good with somthing else in unity.
One of the issues with game managers is that they usually end up as singletons or static objects. Statics and singletons are fine for certain things (loggers, helper methods), pretty much anything that doesn't contain state. The problem with the approach of singletons and managers for everything is that they seem convenient and as a "quick win" but as your project grows in size/complexity, you start to see the shortcomings of singletons. There is a software term called "technical debt", this is pretty much the concept of "kicking the can down the street", you are doing something short-term that can have larger implications as your project grows. This shows itself through statics and singletons in the form of your scripts.objects being "mutable", meaning they can change. If you have a lot of globals in your project that all systems can access/modify, you can no longer rely on the integrity of that state (as anything could change it). So I would say while statics/singletons seem very useful at first, they are difficult to maintain and scale as your requirements change. This is the negative impact that managers can have on a project (not all but most managers tend to be singletons and be responsible for a lot)
From my pov, the singleton pattern should actually prevent your static instance from being changed. If not, the singleton pattern was not implemented correctly. About statics, I agree with you, they can make it difficult to be tracked and also be cleaned when it comes to threading and keep track of what is still running or not (which can always be an issue, static or not :D)
Functionally there is no difference between a static object and a singleton in terms of use-case. You could say a singleton does provide a level of encapsulation (private constrcutor) but the only difference that really matters between the two is that a singleton is an object with a static member, meaning you can use inheritance whereas you cannot inherit from a static class. Beyond that they are the same and provide the same benefits (purely global state). The downside of a singleton is that every system can access it from anywhere. This makes it more conventient as your game logic is "centralised" but then you lack proper boundries how how your system connects and communicate with eachother, so you end up with one "god-object" that becomes the core dependeny on pretty much every system you create. Scripts should be small and have one reason to change "Single Responsibility". If you give your script a general name (GameManager.cs), then what is the responsibility? You could argue maintaining the state of the game world but because of the naming, it encourages your to overload its responsibilities which can be difficult to maintain in a larger project with growing/changing requirements. There is also the argument that it hinders testability but not many people follow TDD in game development
As this becomes a discussion of "whats the best approach" with different viewing points, I leave this conversation to not clutter up the channel more. But thanks for your insights and the short exchange of knowledge 🙂
Functionally there is no difference between a static object and a singleton in terms of use-case.
this might be true in plain OOP singletons, but in unity a singleton can be a monobehaviour, where you could have serialized fields. there's definitely a difference in this environment.
No problem, I didn't want what I mentioned to come off as "preachy" or "this way is the only correct way", a conversation came up regarding statics and I just wanted to offer some potential concerns with over-using them or at least highlight some of the downsides of them in larger projects
You're right I should have clarified that, there is a difference in the context of Unity vs pure OOP
how can I duplicate a VisualElement? Because it doesn't seem I can use Instantiate
It seems like VisualElements themselves cannot be cloned, but you can make the element you want into a UXML document and instantiate that document multiple times in your UI. Only works if that is an option of course. https://discussions.unity.com/t/how-to-make-a-clone-copy-of-a-visualelement/753562. #🧰┃ui-toolkit would be a better channel (if for an editor tool, #↕️┃editor-extensions)
what approach would u use to determine if an enemy vehicle presses the player/someone and damage it like it's crushing?
no physics
okay thanks
well there is kinda physics but agents don't really obey it
I can use a rigidbody and a trigger collider but how to filter out situations where, like, a tank is rotating and a player touches it's back turning away so they move the same direction and no damage should be done
Btw instantiate as in VisualTreeAsset.Instantiate, not Object.Instantiate which only works for GameObjects and Components
yes, I just found that out, thanks hahaha
I think I can use Physics.ComputePenetration to get a hit direction, some Raycast to get a hit position, use Rigidbody.GetPointVelocity with that position, calculate angle inbetween velocity and de-penetration, and if it's lower than like 60 do tick of damage
no, wait... kinematic rigidbodies don't really have velocities do they
What else singleton can be? I only know about instance in assets and scene
"singleton" in unity and "singleton" in general oop have different implementations because of the context/environment
I think Chris was pointing out the fact that because a Singleton in Unity can inherit/derive from Monbehaviour, that gives you the added benefit of hooking up references via the inspector, since the Singleton script is a compoenent that can be attached to GameObjects in the context of Unity. So you get that extra sense of functionality from it being a component/Monobehaviour. This is something that you wouldn't get with a Singleton outside of Unity for example
I'm going to rewrite mission selection map. Had points throwing data at singleton on click. Now have to reference them to enable when level is unlocked
Yes and no. The velocity itself doesn't move the rigidbody but if you are using MovePosition to move it, .linearVelocity will update properly. That I assume is to make the interpolation work. I would think GetPointVelocity would also work then (for rotation, MoveRotation must be used)
I gues for now I ll give up on that idea
hello i hae this code that checks if all enemies are dead, and if they are the game win ui shows up
but it doesnt show up
my enemies are tagged with "Enemy"
Is the log printing?
what
The log you put in LevelCleared()
is it printing in the console?
how do i check that
by looking at the console
If you're doing unity development without your console window visibile at all times, you are basically flying blind
Why did you put the log if you didn't intend on checking if it printed 🤔 ?
no i don't think it does
then you are never getting to where enemiesAlive is less than or equal to 0
You should add more logs
put another one inside EnemyDied
like:
Debug.Log($"An enemy died. There are {enemiesAlive} enemies remaining");```
See if that is printing as expected whenever an enemy dies
and make sure the number of enemies it thinks there are is accurate
it doesnt print
then you are never calling EnemyDied() when you kill an enemy
on enemy died
that's why nothing is working
oh i think i know
oh im deleting enemies myself
is this not working because i am deleting the enemies myself?
IDK what you mean
you mean the Destroy()? That's irrelevant
im not shooting them in game, i just delete them from the scene when running
yes then of course
that's the problem
but then the code doesnt execute
it's not going to run your code then yeah
Hmm. Level manager rabbit hole
it appears it does not work
i added a log ot the enemy healt script
and not even that shows up when the enemy gets shot and killed
Im ggonna spawn a prefab inside of an object but how can I control where the prefabs appear on the object?
First I would make all variable and functions, which won't be accessed by anything else "private". Also private is default, so not necessary to put it. For in inspector referencing you can serialize field [SerializeField]
Parenting and anchors.
I have 0 clue what that is
It's UI or game object with text?
huh?
Searching by tag is much slower, then layers. Enemies get instanced (spawned in scene) or manually placed?
Go to #📲┃ui-ux they will help you
it works now
thanks
but i have found a new really bad bug i need to fix
god i hate programming
Writing cleaner and more stable architecture of code helps with bug spotting
im not the one for code writing to begin with
You can maybe find people to do Collab.
yeah this is a solo project
I have 1 solo and 1 duo project. I better to work with somebody, easier to focus on your part of job
solved it with grid layout group
i am working this solo mostly so when i shit on devs for ruining or releasing a bad product even though they have 5 plus devs with years of time and smartasses come to defend them with "uh make your own game then" i can show them i did
you could mabye have like kinda somehow said that
i'm looking at the indie stone with project zomboid and half sword @elfin pike
and such
I think you responded to the wrogn guy💀
oops
lol nw
You could have solved without any extra classes
With increasing Dev count, it becomes harder to manage. Yeah, good luck with that
somehow me trying to gamedev for a long time curbed my attitude like that
I can't say it's hard but it's pretty tedious to do anything
I don't really have several lifetimes to make all I want let alone to make all I want polished
So I becoming the part of the problem and... I don't mind
Hello, i know this might not be a code related question, but how do I stay motivated in making my first real game? (A 3 months project) I feel bored when im making it...
why did you start making it?
Because i wanted to explore game dev, i have learned unity for a month now and i know the basics, i have made 2 simple games and now i want to make a real game, something really playable, but im not motivated rn
Go play some good games and get inspired
I already have the game idea (even tough its not the best but i will learn real gane things at least)
Its just that when I really start making it i get bored easily
reduce the size of your scope
It is already a simple game
I would be happy to help
..depends how you define "simple" make smaller wins you set yourself for the day.
or maybe take a break from it and come back to it when you're more inspired.
you can easily burn out
i just finish the tutorial ypee
With what? If you mean with code thanks but i still need to learn alone
What idea you had for the game?
btw game design discussions overall should be in a thread in #💻┃unity-talk
this is a coding channel
The idea is that u are a lighthouse keeper
count the number of times the user presses the key
and have some target number of times they have to press it
if they press less than the number, they fail
(within the time period, of course)
i want to make like when you stop spam for less than a 0.5 sec the spam bar decreases until you fill it up again?
make it continually decrease and add some to it every time you press the button
what's a "spam bar"? You've underspecified the problem.
Sounds like maybe you want a continually decreasing number and each press increases it by a fixed amount
Quick example: @blissful stratus
float startingValue = 0.5f;
float failValue = 0f;
float winValue = 1f;
float decreasePerSecond = 0.5f;
float increasePerPress = 0.1f;
float currentValue;
void Start() {
currentValue = startingValue;
}
void Update() {
currentValue -= Time.deltaTime * decreasePerSecond;
if (Input.GetKeyDown(KeyCode.P)) {
currentValue += increasePerPress;
}
Debug.Log($"Current value: {currentValue}");
if (currentValue <= failValue) Fail();
else if (currentValue >= winValue) Win();
}```
thx man🫡🫡
Hello, I am not certain if this is the correct channel to post in so please correct me if this is the wrong location so that I can move this plea for help.
I am currently trying to build a project that I have been working on for a while however whenever I do so it just is the default unity blue colour after a grey screen that fades away. In addition to that the frame rates exceed my frame cap of 240 which suggests to me that nothing is running and the resolution becomes 4:3 when the game should only be running in 16:9. Please could I get some help?
These are my build settings as well
And this is how it should look like at launch
First thing to do is check the player logs
(make it a development build so it writes logs)
alright
you'll also see errors in-game in a development build
Hey does anyone know where I can find any resources for making a 3D platformer in Unity?
I have the models and very basic stuff but idk where to find the right tutorials and ppl lol
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Could I please ask where it writes the logs?
!logs 👇 go to the documentation and find the player logs
Editor logs
Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log
Unity Hub
Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs
This just makes things more confusing
I think for some reason it is rendering 1x1 pixels
I have no clue why
I changed the scene and it rendered the main colour from that scene which is red
Just this now
Sounds like maybe a script of yours is behaving unexpectedly
do you ahve any code in your project that sets the game resolution?
I would search for that
what do you mean "main colour"?
The most dominant colour on the screen
maybe average or median pixel color 😛
do you mean that you changed the background color of the camera?
why does the flashlight's rotation only lerp when moving up and down
if not, show what you actually did
After changing the starting resolution in the player options the splash screen works but past that it reverts back to the issue
!code 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
is the flashlight a child of the player object?
or the camera object
ehh, I would rather not-
It's a rather cringey easter egg scene that I made in 5 minutes because I was bored and wanted to do something a bit more silly
yeah so:
transform.Rotate(0, mouseX, 0);```
when you rotate the player, the flashlight will rotate immediately with it
since you're rotating only the camera for up and down, THEN your code with the lerp matters
oh, so the flashlight is parented
ohhhh
got it thx
If you want to keep it parented to the player, you could remember the rotation from the last frame and lerp from that to the goal rotation
The answer here would be to either unchild the flashlight entirely and control its position/rotation via script, or to rearrange the hierarchy so there's a non-rotating object that is the parent of the flashlight but still moves
or yeah... hack it like Fen described
I think that makes more sense, yeah
if Player doesn't rotate and PlayerObject does, that will work
yes it worked
ah
So I think I found the issue
This is called at start and if you don't already have a save file
The settings.resolution variable just stays at the default 0
that'll do it
mm!
That does sound like it could have some sort of potential
tbh
I don't know if the unity editor was rendering at 0x0 or if it rounded up to 1x1
I have no idea how 0x0 would work, so probably the latter
it turns into an audiobook
I feel like I remember there being some sort of game out there which was just completely black, it had no graphics and you had to rely on sound in order to do things therefore simulating blindness.
May have been a vr game, I am not entirely certain
Also, I have just applied a fix and tried commenting out all the code that could change the resolution
It still
Doesn't work
It seems that
Even if there is no path to this part of the code
Even if it is setting the resolution to something higher than 0,0
As long as the code exists it will do the glitch
I followed a basic 3D platformer tutorial and my character isn’t detected as “grounded” when she is standing still
Is this a common issue
you likely followed it incorrectly. show the relevant setup and code if you want help
hold on
Draw gizmo
i’m like extremely new to this what does that mean 😭
it's an unhelpful response until we actually know how you are performing the check. show the relevant details
send the code here
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
ain't nobody trying to read those photos. share the code correctly
uhhh ok
Please don't. My eyes burned by what I see
Then use the web page
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Debug.log isgrounded. Charactercontroller settings maybe not right
For love of god don't get components in update function. You can do it in start or awake
@autumn quartz Did you fix it?
Hey guys I have a raycast that when I look slow left it tries to go right and back to left making this weird bounce back and forth effect. I tried smooth options but that didn’t fix it. My cam is in update and the ray is in late update. Someone recommended to change the execution order of the PocketPath script so that it always runs after the camera script but im a little lost on how to do that besides the late update method which didnt work. any help is appreciated
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PocketPath : MonoBehaviour {
[SerializeField] private float maxDistance = 200f; // configurable max distance for the ray
private void LateUpdate() {
// Create a ray from the center of the camera
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f));
// Draw a yellow debug ray in the Scene view
Debug.DrawRay(ray.origin, ray.direction * maxDistance, Color.yellow);
}
}
project settings -> Script Execution Order
doubt thats the fix
same but that is how to change the execution order
You are drawing a ray away from the camera so I'd expect it to look weird yes, if visible at all
What do you expect to see?
btw if you just want a ray from the center of the camera, you don't need to use ViewportPointToRay, just use the camera's transform.forward as the direction and it's transform.position as the origin
Slightly different because then it doesn't use the near plane position, but that often doesn't matter
thank you
I have a class that has a ushort value _amount and a string value _additionalOperations
inside the class, I have a short function called ExtractValue().
how would I have it read the string as a mathematical operation ( probably testing if its valid using regex ) and return it?
( example: _amount of 6 and _additionalOperations as "{_amount} / 2" should return with 3)
you think it could be my camera jitter. I want to think that but the raycast is bouncing the opposite way im looking so im not sure
Is your camera a child of a rigidbody, does the rigidbody use interpolation, how's the rigidbody and camera being moved, etc.?
yes to child and yes to interpolation.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerLook : MonoBehaviour
{
[Header("References")]
[SerializeField] WallRun wallRun;
[SerializeField] public float sensX = 100f;
[SerializeField] public float sensY = 100f;
[SerializeField] public float YPlayerStartDirectionY = 180f;
[SerializeField] public float XPlayerStartDirectionX = 180f;
[SerializeField] Transform cam = null;
[SerializeField] public Transform orientation = null;
public bool invertYAxis = false;
public bool invertXAxis = false;
float mouseX;
float mouseY;
float multiplier = 0.01f;
public float xRotation;
public float yRotation;
private void Start() {
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
yRotation = YPlayerStartDirectionY;
xRotation = XPlayerStartDirectionX;
}
private void Update() {
mouseX = Input.GetAxisRaw("Mouse X");
mouseY = Input.GetAxisRaw("Mouse Y");
yRotation += mouseX * StagesSenseManager.Instance.SenseValue * multiplier;
xRotation -= mouseY * StagesSenseManager.Instance.SenseValue * multiplier;
xRotation = Mathf.Clamp(xRotation, -90f, 80f);
cam.transform.rotation = Quaternion.Euler(xRotation, yRotation, wallRun.tilt);
orientation.transform.rotation = Quaternion.Euler(0, yRotation, 0);
}
}
assuming orientation is the rigidbody, you are breaking the interpolation by modifying its transform which is causing jitter
I think it's a "camera container" object
Seen many tutorials teach that lately
Or maybe it's the chatbots
it was a youtube video
How do you move the rb? What boxfriend said is the usual cause
I want to say its this. this is in update
_movementDirection = InputSystemHandler.Instance.PlayerInputActions.Player.Move.ReadValue<Vector2>();
horizontalMovement = _movementDirection.x;
verticalMovement = _movementDirection.y;
moveDirection = orientation.forward * verticalMovement + orientation.right * horizontalMovement;
note: no math more complex than just addition, subtracting, division and multiplication will be required, just those operations and the ability to parse variable names
Also pro tip, use a low time scale to debug jitter/interpolation issues
that does not move anything, this is just calculating the direction and distance.
you're right one sec
void MovePlayer() {
if (isGrounded && !OnSlope()) {
rb.AddForce(moveDirection.normalized * moveSpeed * movementMultiplier, ForceMode.Acceleration);
} else if (isGrounded && OnSlope()) {
rb.AddForce(slopeMoveDirection.normalized * moveSpeed * movementMultiplier, ForceMode.Acceleration);
} else if (!isGrounded) {
rb.AddForce(moveDirection.normalized * moveSpeed * movementMultiplier * airMultiplier, ForceMode.Acceleration);
}
}
and how do you rotate it
the camera? or the rigidbody
the rigidbody
i dont think I am
and you are absolutely certain you aren't rotating its transform? when i said "rigidbody" i was referring to the entire rigidbody object
I dont believe so. I just played the game and moved around while player selected and didnt see rotation change
the only thing rotating is my camera holder
would this still be a cause even if my rigidbody rotation isnt changing?
that would only be the case if the first part of that message was true
i think I fixed it
unless I misunderstood your question, can't you use something like NCalc ?
thank you for this
and thank you for this
The ray is finally smooth cause of that thank you I switched it to cam forw and it works now. Much appreciated. Ive been stuck on this bug for so long thank youuu
👀
id have to look into this
from a surface level it looks like what I need, if not a bit overkill
i think
yeah probably lol
yeah its what im looking for but waaaayyyyy overkill
maybe start with some Regex for safely parsing math characters & then do the evaluation ?
i also wanna add my own custom little thingies ( like being able to type R(a, b) and it gives a number between A and B )
so i think regex would also help with that i guess
It might.
there is probably some really simple solution but this is going way over my head lol sry thought I could figure it out my brain aint mathin rn
if anything ask here https://discord.com/channels/489222168727519232/1390355039272439868
aigh, i wont forward my original question bc im expanding it a bit
@final trellis FYI Unity also has this:
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/ExpressionEvaluator.html
It used to be in UnityEditor but seems like they moved it to runtime also
Not sure if you can add custom operators/functions tho...
oh hell yeah
dammit
i'd have to parse the custom stuff first
but i guess the actual evaluation parts solved! just need to do crazy shit with regex i think???
The ExpressionEvaluator code is readable with IDE if you go to the source
Maybe you can use it as reference
yo, can someone help me? im making a 2d videogame but the collitions just dont collition
(I'm not a lawyer)
For some reason my Camera follow code randomly broke and completely stopped working despite it working perfectly before. Here is my code if someone could help me find the issue: ```using UnityEngine;
public class PlayerCam : MonoBehaviour
{
public float sensX;
public float sensY;
public Transform Orientation;
float xRotation;
float yRotation;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
// Get mouse input
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90);
// Rotate cam and orientation
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
Orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}
}
How are you moving the object that has the rigidbody?
Check for console errors or other scripts you have added that could be modifying the camera (and make sure your camera has this script)
this is the script
i guess there is an obvious error im not able to see
but according to chat gpt the script is rigth so i dont know
Guess it's unsolvable if chatGPT can't figure it out.
Possibilities:
- This script isn't actually on your player
- You have too low (or no) speed value. You shouldn't use default values for public fields as they're overridden by the inspector.
Saw the first screenshot, looks like you are using a kinematic rigidbody on the character
If you do that then you are expected to do your own collision checks
it is
the player can actually move
the problem is that it passes through objects
i also tried in dinamic
it doesnt work neither
With dynamic you need to use rigidbody.linearVelocity or AddForce to move it
Not MovePosition
Actually iirc MovePosition is fine with the 2D physics engine
Moves the rigidbody to the specified position by calculating the appropriate linear velocity required to move the rigidbody to that position during the next physics update
Same does not apply for 3D though
Yeah, though the doc also says
Note: MovePosition is intended for use with kinematic rigidbodies.
Still unsure what the limitation here is though, haven't tried it too much
I think the kinematic collision wasn't working because this full kinematic contacts wasn't enabled on the RB 🤔
Sounds weird. It also states:
If the rigidbody is kinematic then any collisions won't affect the rigidbody itself and will only affect any other dynamic colliders.
Sounds like either would be fine. Last time I tried it worked fine, using velocity would probably be safer option though just to be sure
Seems like this only makes it send OnCollisionEnter2D etc. messages but still does not physically collide
This can be a useful feature if detecting collisions is required with details of the contact points and collision normal but without the automatic collision response.
And I can't seem to get a kinematic RB2D to collide with anything when using MovePosition 🤔
So from everything I see, it doesn't automatically apply collisions forces to stop itself on any collision
That's odd. Same with Continuous Collisions? Of course with Discrete you can set it behind a wall and it will teleport there
Never really done 2D games myself but I'm pretty sure I did test this couple years ago and it did collide correctly.
Yeah, tried with CCD, doesn't work
I have a small but annoying issue with events.
I have class that just has static actions, and I can attach/listen to such actions, but not trigger an event. I have an error saying the action does not exist in the type...
public static class RunnerEventSystem
{
public static Action<float> OnPlayerJump;
public static Action<float> OnPlayerOutOfFuel;
}
private void Awake()
{
//That's okay
RunnerEventSystem.OnPlayerJump += Jump;
}
private void Awake()
{
//That's not okay (ignore the fact that it's in the awake)
RunnerEventSystem.OnPlayerJump? Invoke(_jumpDuration);
}
you’re super close. The issue is just a small syntax mistake.
In C#, the null-conditional invoke operator must be ?.Invoke(), not ? Invoke().
So this line:
RunnerEventSystem.OnPlayerJump? Invoke(_jumpDuration);
should be:
RunnerEventSystem.OnPlayerJump?.Invoke(_jumpDuration);
It was indeed a small issue -_-
Haha yeah, those are the worst ones
C# is super picky about tiny syntax details, and ?.Invoke() is one of those things that’s easy to mistype when you’re moving fast. One missing . and suddenly the compiler acts like the whole thing doesn’t exist.
If you running into this and your IDE isnt telling you the error, you might have not setup your IDE correctly.
!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
• :question: Other/None
static events 🤕
This is probably the best channel for this so here we go
I want to implement Lua scripting support for my project and I would like to ask for some recommendations as to which library/store asset would be the best for my usecase
The idea is that the scripts would be read at runtime and each script file would be a definition of behavior for singular things like events, skills, etc
Ideally being able to read properties and call methods on specified unity gameobjects with as little friction as possible
If it's their own project then it's fine
I'm not trying to mod someone's game if that's what you are implying
Oh, good to know, because I was told otherwise. Alrighty then 🙂
Yeh, forget my message then, just quoted what I was told, but that was obviously not 100% correct. So go ahead 🙂
I worked with some editor scripts, where you would use a dropdown reflection list to get all methods of a gameobject, that supported the singleton pattern, so on runtime, it will call the Instance + methodName on that runtime singleton object. So adapting this to your situation using predefined strings for methods/types might also work in this case.
I guess, it depends on how complex you targeting your system to be. This is a simple approach for a simple task, could be extended but might not be the correct solution if it gets way more complex.
The exact complexity is something that I have yet to determine, as this project of mine is in the very early stages
they're both adequate
oh alr
i mean i mostly use vsc I'm new to game dev haven't used vs for a while xddd
Either way I first need to implement anything and experiment with it which leads back to my question about library/store asset recommendations as to what should I use for Lua support
Hello !
Im trying to access the __SequenceChangeLevel__, i've created a universal trigger zone that usually can access gameObject's script's function but for the first time, it doesn't work. The __SequenceChangeLevel__cannot be found nor executed.
Am i doing a mistake ?
In this other example, i do manage to access the __activate__ function so i don't know what im doing wrong.
{
Invoke(nameof(Activation), timeBeforeSpawn);
AddEnemyCount();
}```
i know it's not the question but whats with the underscores
whats in here
also another thing that doesnt matter but most people don't put scripts in the name of their script, it's redundant
you cant expose a function with two parameters. because the activate has one float, it is considered as a dynamic one, which is supported by the default events GUI
The part with "No function" usually shows you all public methods that have one param, like a float, string or boolean if the event on your inspector class supports it. But there is by default none for multiple params. You gotta create that custom editor for yourself afaik
It's just so i can find it easier on the list !
And all of that :)
Its sorted alphabetically, so should not be too hard to find while sacrificing readability of your code 😉
Alllriiggghhttt... Thank for the explanations ! It so much better now that i understand !!!
I have to extend my explanation, just to not give half baked information. So the "no function" part shows your functions, when for example a UI Slider event supports the float value. So instead of hard typing it in the even,t you can chose the dynamic one and it will call it with the slider event (just for example). But you can still get the method from the lower alphabetically sorted part of the list, where you can type in the float you want to pass in too. Just to make sure, you know both ways how your public methods are handled with one param 🙂
gettings "IOException: Sharing violation on path".no idea why. how i understand error, something else is accessing file, but only one class instance, has access to file
File.WriteAllText(SavePath, json);```I have same setup in other classes, but they dont throw error
@wintry quarry thank you for telling me to log pretty much everything. i've fixed half of my problems in the game now and repairing code is way easier
You should log your path, what is it. Are you trying to access a path you are not allowed to?
Path is allowed, I created it in class
Well, the error says, something is not allowed on your path. So you are trying to access "something", thats not allowed. Maybe you are trying to write a file while reading it, maybe you got the wrong path in and tried to save somewhere on the system.
Maybe I have to close it after writing
as long as we dont know your entire code of accessing the file, we can only guess
I can we also load function, which is also 2 lines
and when do you call them? right after? at the same time? give some information...
Load called in start of class life time. Save called in end of it at destroy
and no other script is accessing the same file?
yes, because i create filePath in class and in it also work with it
not a coding question but can someone tell me how to get rid of this empty area, its annoying me
I assume your camera clipping planes are working here. check the camera settings for your scene camera
#💻┃unity-talk is for general questions
That area is like that because you've focussed on something large, and then moved closer
Select the green plane, press F
tried changing to your settings, still didnt really fix it
pressing f didnt really fix it either
Not my Settings… its your scene view settings cutting off with occlusion culling. Play around with it
Yep! Debugging code is a skill that is often underappreciated.
thats another view mode. I think its called orthogrphic view idk how to fix it tho. I mean i used to but forogt. Ask google
you click the button that says iso
i'm still not really sure what the expected behavior is tbh
see how the grid stops part way, not reaching the edge of the window.. it's being cut off (would cut off the green plane too).
ah
Looks like I'm correct I open file but don't close it
Try to move your camera with WASD while holding mouse left click
Looked up in "learn microslop com" about "FileSystem.WriteAllText Method". It says, that file should close after function finishes
the settings shown are probably causing the problem
the near clip plane is at 17.7 meters
so anything that's closer to the camera than that will not be rendered
turn on "Dynamic Clipping" and then hit F to focus on the object
this will adjust the clipping planes to something sensible for whatever you have selected
(also, this is a problem with the clipping planes, not with occlusion culling)
occlusion culling is used to disable renderers that are completely covered up by another renderer, and that only happens in the scene view when you have the Occlusion window open
From what I'm seeing in stack overflow, maybe 2 file streams get created. 2 file streams cant acces 1 file
Why isnt my ray shooting out the center of the camera holder? OR even the camera. Its not even the right direction.
cs
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(CameraHolder.forward), out hit, 5))
{
Debug.DrawRay(transform.position, transform.TransformDirection(CameraHolder.forward) * hit.distance, Color.yellow);
}
Is this script on the camera holder? Does CameraHolder refer to a transform component? What's the purpose of the TransformDirection?
transform.TransformDirection(CameraHolder.forward) this is definitely wrong
It should be:
Physics.Raycast(CameraHolder.position, CameraHolder.forward, out hit, 5)``` and
```cs
Debug.DrawRay(CameraHolder.position, CameraHolder.forward * hit.distance, Color.yellow);```
how should I store persistent data if the gameobject won’t exist sometimes? Asking because if I’m reading correctly, File.WriteAllText() will overwrite anything I have saved in another file if I can’t call that gameobject’s save function, then it won’t have anything later.
(I don’t have access to exact code right now, I’m planning out in pseudocode while at school and kinda wanna know so I don’t run into issues later)
As in, if I have a float that a script will use, but the script only exists sometimes, should I use another class, a modifiable scriptable object with the fields, a different save file, etc, if that float should save its state between all instances of that script
Surely the game doesn't need to save the data of a gameobject that doesn't exist at the time the save is made
it’s player data, but the player controls different things at different times. At those times, I’m in a different scene and the other script no longer exists
i can provide better examples of what i’m trying to accomplish in about 3 hours-
If you need to transfer modified data from one scene to another you can save it when the scene ends and restore when returning
the data is different for each of the scenes
the original one needs its original data
if that makes sense
but the script doesn’t exist and I can’t call the save anymore
I also learned how to save like 2 days ago and its barely functional so maybe i’m misunderstanding how it works/ i just did it wrong
i’m just gonna re-ask the question in 3 hours, or maybe ill figure out between then. Sry if my bad code is giving you an aneurism
You save the required data when it is about to be destroyed, not at some random point in the future when that data doesn't exist anymore
my question is how to handle that data being overwritten cause apparently I’m supposed to use one json file to save to
and save in such a way that doesn't overwrite data
either multiple files, or a json or something that adds data to it rather than completely writing a file every time
Save to multiple files it is. Didn’t know if that was bad practice. ty
You should have one save manager that handles making saves anyway, so instead of having each object handle saving independently they tell the save manager what to store and the save manager handles it centrally
don't see why it would be, probably depends on the situation
is there any "fast" method of getting all types with attribute at runtime? I know about edit time TypeCache class thingy, but what about runtime? just iteration over assemblies is utterly slow even if filter out Unity/System assemblies before it
I need it do it once btw, but also want to avoid hickup on startup of the runtime when it do the iteration
what is the purpose of this? because a source generator might be a better option than doing it at runtime
why do you need this?
i'd rather have this beforehand, not during runtime . . .
I don't have a "runtime only" criteria btw, like I'm open to any solution to look up in google. I wrote about runtime gathering and iteration over assemblies only because I don't know anything else or how to do it in any better way, lol.
I'm writing something like attribute based "DI"-like thing just for learning sake and my own pet project usage.
Pretty much
You should be able to do it once and hang onto the results after that, of course
you should research source generators, particularly incremental source generators. basically it will allow you to write code based on the existing code in your project, and you can make it do that only for types that have a specific attribute
thank you! I will try to wrap my head around that
Hey
So uh i was following GMTKs tutorial on a flappy bird game, and in the update function thing he used instantiate and delayed it by setting a timer to 2 and then added time.Deltatime to t every other frame and reset back to 0 afrer the spawning. But when i increase the number from 2 to like anything the delay doenst change between the pillars spawning
Are you changing it in code or in the inspector
In code
in visual studio
the code defines the default values. The entire point of the variables in the inspector is to override the default values.
change it in the inspector
when you add script on a gameobject, once the value is Serialized by unity with public or [SerializeField] private the inspector takes precedence.
changing in the code will have no affect unless you were to reset the script or re-add it.
the C# field initializers provide the initial value for the field; however, Unity then plugs its own values into those fields after creating the object
therefore, the field initializer only matters:
- when creating a brand new object, if the field is serialized
- for non-serialized fields
i have anystate connected to 3 animations one if them is "hurt" animation it uses a trigger variable after the paramater triggers and the animation plays the transition has exit time but it is skipped if another anystate condition is triggered how do i make the transition's exit time unskippable without turning the hurt paramter in to a bool
Any State really means any state
It's not very useful for anything non-trivial
my VRChat brain said "oh, use a parameter driver to set a parameter when you enter the pain state, and then reset it when you exit the pain state"
ok i'll be more careful what to put therre
Consider using Animator.Play() to forcibly enter the pain state, rather than using an Any State transition to get there
this does mean that your animator now depends on a script to work the way you want it
(well, it already did for parameters, duh, but now it requires more than parameters)
using UnityEngine;
public class CharControllerScript : MonoBehaviour
{
public float speed = 5f;
public float jump = 2f;
public float gravity = -9.81f;
private CharacterController cc;
private Vector3 velocity;
float maxReach = 300;
public GameObject Bed;
public GameObject TimeManagerObj;
void Start()
{
cc = GetComponent<CharacterController>();
}
void Update()
{
Vector3 move = transform.right * Input.GetAxis("Horizontal") + transform.forward * Input.GetAxis("Vertical");
cc.Move(move * speed * Time.deltaTime);
if (cc.isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
if (Input.GetButtonDown("Jump") && cc.isGrounded)
{
velocity.y = Mathf.Sqrt(jump * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
cc.Move(velocity * Time.deltaTime);
}
void FixedUpdate()
{
// Will contain the information of which object the raycast hit
RaycastHit hit;
// if raycast hits, it checks if it hit an object with the tag Bed
if (Input.GetKeyDown("e"))
{
if(Physics.Raycast(transform.position, transform.forward, out hit, maxReach) &&
hit.collider.gameObject.CompareTag("Bed"))
{
Sleep();
}
}
}
void Sleep()
{
TimeManagerObj.GetComponent<TimeManager>().totalSeconds = 86400f;
}
}```
this is my character controller, i have assigned a cube the "Bed" tag, and the raycast and "Sleep()" function work but only on one specific corner of the bed obj for some reason ??
First off - GetKeyDown in FixedUpdate is a bad idea
second - yeah. split up the if conditions and add a log showing what you actually did hit, if anything
Okays thanks!
e.g.
if (Raycast(...)) {
Debug.Log($"Hit {hit.collider.name} with tag {hit.collider.gameObject.tag}");
if (hit.collider.gameObject.CompareTag("Bed")) {
// hit the bed
}
}
else {
Debug.Log("hit nothing");
}```
For some reason this code is rotating the Player along the wrong axis. Could someone help me fix it because I don't know what's wrong: ```using UnityEngine;
public class PlayerCam : MonoBehaviour
{
public float sensX;
public float sensY;
public Transform Orientation;
float xRotation;
float yRotation;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
// Get mouse input
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90);
// Rotate cam and orientation
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
Orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}
}```
don't use deltaTime for mouse input btw
it's already per frame
Yeah idk why I used it
is Orientation a child/parent of this object?
yes it is
which one is it
it is a Child of the "Player" gameObject
...i don't know what that is in relation to this object
i'm not looking over your shoulder
Its a child of the gameObject this script is attached to
so it's the current gameobject that's being rotated incorrectly as well?
Yes
usually (as far as i've seen) you would have the camera as a child of the player, and you would have the player yaw and camera pitch separately
(probably not directly related to your issue, just commenting on the setup)
is the player rotated to begin with, in edit mode?
No
you could describe/show how exactly it's rotating incorrectly
It is rotating the gameObject along the X and Z axis instead of the Y axis. (Ie its rotating the player vertically instead of Horizontally)
the values in the inspector show the x/z values changing?
Yes.
is the player a child of anything else?
It is not a child of anything
Let me see if another script is causing this issue.
It is not because of another script
Im just gonna rewrite the code in order to find out where this issue is occuring
anyone know how i could make this cinemachine camera only move when the player is leftclick and dragging instead of any time the mosue moves ?
