#💻┃code-beginner
1 messages · Page 807 of 1
This is moreso a question about vscode's workspace and how it handle new files
when I try creating a new file Project\Scripts\myScript.cs through vscode's file explorer, it does not get automatically added to the workspace or the Assembly-CSharp.csproj, and I have to manually modify and add that new file
Is there something I can do to make files get automically added?
Example:
It should be added after unity compiles the file. Assuming you have vs code configured correctly.
what does it say when you mouse over it?
It's probably recommending a collection initializer
so it doesn't throw an error or warning
is there a lightbuln in the left margin
Hover over the mixer group counts or the add method.
e.g. MixerGroupCounts[soundEmitter.SoundData.mixerGroup = [soundEmitter];
no
maybe it's signalling that I can simplify this?
ah ok
try hovering over different parts of the line
doesn't say anything
as in it just shows what the thing is like in the screenshot above
Try Ctrl + . on the line
ah you're right
Try hovering over the new. It seems to have an underline.
and now I'm seeing the lightbulb - wasn't there before because I didn't click on the line
yes its showing the message in the new instead of on the next line
thanks guys!
I have a prefab called FloatingMenuIcon which has a has the following script attached to its primary object :
```
public class FloatingMenuIcon : MonoBehaviour
{
public Image image;
}
In another class I have a property:
```
private FloatingMenuIcon iconOpen;
```
which I populate via :
```
iconOpen = Instantiate(iconPrefab, iconPanel.transform);
```
Can someone confirm. The actual way to make this prefab active/inactive is via:
```
iconOpen.gameObject.SetActive(false);
```
Just feels a little wierd and I want to make sure I'm not missing something. Thanks
!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.
what does SetActive do?
is that what you want to happen?
Yes, but I want to ensure I am doing it correctly
oh, so it doesn't actually de/activate when testing?
by the way, SetActive activates and deactivates the GameObject. it's different from just hiding or showing the ui element . . .
deactivating and activating a GameObject will stop all of its scripts from running Update and every component is disabled . . .
Everything seems to be working fine. I'm just suprised I am using .gameObject.....I'm new to all of this
.gameObject will access the GameObject the FloatingMenuIcon script is attached to . . .
Yes the concept of "active" is a property of the GameObject.
Another option would be to disable the specific visual componeents you want to hide instead of the whole GameObject, if you had a desire to leave other things active/enabled
if you only want to show or hide the graphic, you can use a CanvasGroup component or disable the Image.enabled property (from the Image component) as well . . .
Components can be enabled, but objects can be Active. A gameObject contains many components, so if you want to deactivate the whole object you need to go from the component to the gameObject it's contained on
Ok. Makes sense. Thanks for explaining. I appreciate the help.
void Interact()
{
RaycastHit hit;
interactionRay.origin = mainCamera.transform.position;
interactionRay.direction = transform.forward;
float interactionDistance = 3f;
if (Physics.Raycast(interactionRay, out hit, interactionDistance))
{
if(hit.collider.gameObject.TryGetComponent<IInteractable>(out IInteractable interactable))
{
interactable.OnInteract();
}
}
}```
I have a class Node : IInteractable and imlpements OnInteract();
Would this be a suitable to call the function (regardless of which class implements IInteractable)
The code does not function and I would like insight on why this fails to run (The function just Debug.Log("Interacted with" + this.name)
ok so sounds like 2 separate questions
the latter, debug to see where the flow of code reaches
im using the same style system for my interactables..
- IInteractable interface
- Raycasts
- and TryGet
debug like guy mentioned ^.. find out and make sure that each step of the code is running how it should. that will help u sniff out whats wrong.. i just had an incident where i culdnt get the Interact button press to work w/ the raycast but finally i found out I had it set to have to hold it .5 a second b4 the input system throws the event..
gizmo's help too.. but most likely the raycast is working as usual but something else is wrong.
ofc i cache my interactable the entire time im looking at it..
so then when i press interact i just call its .Interact() method from the cached
oh i meant to point out im using the TryGetComponent(out XXx xxx) signatur
they're using the same signature
well, (minus this part) is wht i mean..
not sur what the specific terminolgy for it * is
it's the same signature, you're just letting it be inferred
ahh oky ^
the explicit type parameter/generic?
ahh yea that makes sense..
huh yeah i don't know what the official term in c# is, that's the ts term lol
yeah they're type arguments
<illtrytoremember>
How do I implement gyroscope/phone-tilting controls with the new input system?
I for some reason cannot understand how to actually get it to work:
What type of binding do I add in the Input Actions Editor? Why for some bindings I can choose Angular Velocity [Gyroscope], and for some not? How do I access the values later down in C# code?
I know this issue is easy to fix - but I'm to frustrated or tunnel-visioned to fix it by myself. Any help will be dearly appreciated.
perhaps ask in #🖱️┃input-system
... Oh
How do I access the values later down in C# code?
i would assume the same way as how you use any other input
Yeah, just noticed - sry, my bad
Soo, nothing special? No voodoo magic?
why would you assume so
Dunno honestly - try to expect the unexpected, ig?
Why for some bindings I can choose Angular Velocity [Gyroscope], and for some not?
probably to do with the type of the action
yeah no don't do that, that just complicates stuff for yourself
not code per se but is anyone else having extremely slow github clones today? normally it takes no longer than 3 seconds, but today its taking 10s of minutes
I thought it might be my AV or internet but I turned AV off, and internet is currently fine
Welcome to GitHub's home for real-time and historical data on system performance.
i think it had issues like last night or something
says it doesn't have any right now though
weird
also it was super slow earlier for like 50% and then the rest it zoomed like normal in a second
may just be an isolated issue with some specific cluster or something like that
maybe, I just hope BitDefender didn't randomly break something without notifying me
Starting game dev here. I want to create some games, but i'm unsure of what audience would be best. Can you tell me what types of games and on what plaform is most popular now?
you should probably focus on learning first before thinking of optimal markets and genres
its a long road ahead
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
don't limit yourself to that kind of thing, just make what you want. otherwise you'll just burn out
I want to make it all, i have very small games in mind that i will use to learn, and larger games in mind once i learn some concepts. right now I can make simple games, but i just want to know what most gamers like now. i'm kinda old, so i don't know what's being played right now. like... NES old.
different gamers will like different things, all genres have an audience, it's not like there's going to be one genre that 80% of all "gamers" hyperfixate on
why not make the type of game you'd like to play yourself?
if youre trying to optimize your game for a certain audience youre sort of setting yourself up for failure in the long run
consider that the markets for popular genres are highly contested
if success is what drives you, youre better off doing something unique
a quick google seems to suggest the most popular genre has <20% market share
I will. i guess my question would be what platform is utilized most. i don't see many people playing on actual PC setups anymore.
that'll basically just have the same answer lol
plenty of people still play on pc though.
pc is quite popular because of steam, console is more expensive though for publishing
but if you don’t have any games what are ya gonna publish lol
additionally, you’ll likely want to make some kind of advertising or get your game out there so that no matter where you publish, people will actually know your game exists
you’ll find players on every platform for every genre, so it’s really your call
what if something doesn't work and you have no idea how and why, are some tutorials are out dated?
you can probably start by asking here.
are some tutorials are out dated?
yes, because time doesn't stop flowing
9 times out of 10 it's user error when it comes to code related stuff though
unless it's a tutorial from before 6.1 and you're on >6.1 and the error is the input setting
even that's still kind of user error since the error tells you what to do to fix it
yeah but technically the root cause isn't your fault
alr
i have a quick question and am wondering if someone could help me? i am trying to make a menu screen for a simple game i am trying to make but it doesnt seem to work
could someone help me it is my first game
!ask 👇 pay particular attention to the last few points
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
ow i am sorry yeah i looked it up on the internet but i saw some videos but i ceep stuck at the same problem: when i try to add the click event it doesnt show me the option to schoose the script i wrote for it
are you sure you changed the actual class name from NewMonoBehaviourScript?
in the videos it shows the script at the botom of this list but for me it doesnt
yes i changed it into MainMenuManager
What name are you expecting to see and what did you name your class?
Did you change it in the code or just the filename
the class or the file that contains the class? because only the former actually matters
this is what it is called is that right?
that's the file. the class definition is in the actual code
ah so i need to change the name in the code?
yes, you already do see the component in the dropdown menu, you're just not recognizing the name because you've confused the file name for the component/class name
ah ok i see thank you verry much
sorry it is my first time trying to build a game and thougt this woul be a good place to learn
i'd recommend learning the basics of c# outside the context of unity first. that will make learning unity easier because you'll already understand how the code is structured so you'll really just need to learn what the unity types do
hi
hi, this is not a social space
https://nohello.net
public void CreateNewProfileInMenu(Profile profile)
{
GameObject profileInstance = Instantiate(profilePrefab, contentParent);
profileInstance.name = $"Profile_{profile.name}";
Button button = profileInstance.GetComponent<Button>();
TMP_Text[] texts = profileInstance.GetComponentsInChildren<TMP_Text>();
texts[0].text = profile.name;
texts[1].text = profile.CompletedLevelsCount.ToString() + "/4";
texts[2].text = profile.GetOverallScore().ToString();
button.onClick.AddListener(() => ProfileManager.ins.SetCurrentProfile(profile));
}
public void UpdateProfileList()
{
ClearProfiles();
foreach (var profile in ProfileManager.ins.profileList.profile)
{
CreateNewProfileInMenu(profile);
}
}
public void ClearProfiles()
{
foreach (Transform child in contentParent)
{
Destroy(child.gameObject);
}
}
Can someone explain to me why this causes a nullreferenceexception when used? (The UpdateProfileList/ClearProfile method)
If I add them regularly one by one with createnewprofileinmenu, it works fine, but if I destroy (reload the menu) it causes a nullreference exception on the first profile listener
You may want to provide the full error (preferably the entire console window) so we can validate the problem.
Something on that line is null. The same thing a NullReferenceException always means.
Which line is it?
NullReferenceException: Object reference not set to an instance of an object
ProfileMenuManager.CreateNewProfileInMenu (Profile profile) (at Assets/Scripts/MenuScene/ProfileMenuManager.cs:72)
ProfileMenuManager.UpdateProfileList () (at Assets/Scripts/MenuScene/ProfileMenuManager.cs:82)
ProfileMenuManager.ShowProfileMenu () (at Assets/Scripts/MenuScene/ProfileMenuManager.cs:42)
Okay, what's ProfileMenuManager.cs line 72?
texts[1].text = profile.CompletedLevelsCount.ToString() + "/4";
So something before a . or a [ is null
texts, texts[1], profile, or profile.CompletedLevelsCount
One of those is null
Use logs or the debugger to find out which one
The idea is to understand the immediate problem (the source of the nre - likely some variable or collection) and then further figure out why it's null
ok, just thought it was the Button line because that's where it landed before. No idea why it lands here now
So first step is to find out
See what's null
then you can work on why's null
thank you eitherway
It isn't a difficult problem to solve so I hope you've successfully resolved the issue
I think I might have figured the issue
I made profile entries that might be wrong but are still on the json where I get them from
Yeah that's it
does anyone know anything about creating custom navmesh agents ? or some other way of making ai pathing and stuff... im trying to make a car chase game and i need my ai to eherit the car physics and i dont think i can do that with the basic navmesh agent
im stuggling to find anything in google about it if someone has any recources that would be super apriciated
!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.
sorry that was for me
the links are in #🌱┃start-here, btw
gotcha, thanks
just asking if someone knows why this dictionary refuses to take in any values? i keep getting an "Argument Exception: Value does not fall within the expected range." for line 38, and any attempt to print the keys/values doesn't output anything. i've found similar issues online with delegates/dictionaries but couldn't find one exactly like this. the delegate signature matches the stored function signature exactly, i'm pretty sure.
public class Move {
public int handCond;
public delegate void MoveFunc();
public MoveFunc moveFunc1;
public MoveFunc moveFunc2;
public Move(int handCond, MoveFunc moveFunc) {
this.handCond = handCond;
this.moveFunc1 = moveFunc;
}
public Move(int handCond, MoveFunc moveFunc1, MoveFunc moveFunc2) {
this.handCond = handCond;
this.moveFunc1 = moveFunc1;
this.moveFunc2 = moveFunc2;
}
}
public class punching : MonoBehaviour
{
public Sprite palm;
public static handScript RFist; // line 27
public static handScript LFist; // line 28
public float timer = -1f;
public string input = "";
public Move move;
public int buffer = 0;
private Dictionary<string, Move> inputs = new Dictionary<string, Move>();
void Start() {
inputs.Add("J", new Move(1, LFist.Punch, LFist.Punch)); // line 38
inputs.Add("L", new Move(2, RFist.Punch, RFist.Punch));
inputs.Add("JL", new Move(3, LFist.ScrewPunch, RFist.ScrewPunch));
}
...etc
What's line 38
here is the code for the punch/screwpunch functions (stored in a different script)
public class handScript : MonoBehaviour
{
public AudioSource audioSource;
public Animator anim;
public SpriteRenderer sprend;
public playermovement player;
Transform cameratf;
public Sprite fist;
public Sprite palm;
public bool punched = false;
public string move = "idle";
float idlecool;
public void ScrewPunch() {
move = "screw";
sprend.sprite = palm;
Debug.Log("screw");
anim.SetTrigger("screw");
idlecool = 0.3f;
}
public void Punch() {
move = "punch";
sprend.sprite = fist;
anim.SetTrigger("punching");
idlecool = 0.3f;
}
...etc
" inputs.Add("J", new Move(1, LFist.Punch, LFist.Punch)); "
And what is the exact error?
ArgumentException: Value does not fall within the expected range.
punching.Start () (at Assets/punching.cs:38)
Seems like you might have multiple entries with the same key
could be maybe? i dont know, line 38 and the two lines following it are the only lines where i add something to the dictionary, and they each have different keys ("J", "L", "JL")
That isnt the correct exception message for a duplicate key, are you sure its the line with the dictionary Add?
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.add?view=net-10.0#exceptions
the stacktrace says it's from Start and not from Dictionary.Add?
haha great minds
It says it's in start, if the line they're saying is line 38 it'd be that line
but if it were coming from adding to the dictionary, the stacktrace would start from Dictionary.Add, no?
or was that line omitted?
i think so(?), i just ran it again to make sure it wasn't an old line number and it still says line 38. it is in start
Yea the stack would not ommit that im 99% sure
(i mean omitted by OP)
@tender crane could you show the first few lines of the stacktrace
What do those LFist.Punch and RFist.Punch things look like?
It could be on the LFist.Punch?
sorry, how would i pull that up?
i believe those are methods
go to the console window and click on the error, it should be shown at the bottom
rfist.punch and lfist.punch are linked here (rfist and lfist are references to the script that hold these functions)
Save all code changes, re play and copy paste the whole error text here
this is what i see in console
SEND THE TEXT
Where are LFist and RFist assigned?
....huh.
That's the full text, it seems
ArgumentException: Value does not fall within the expected range.
punching.Start () (at Assets/punching.cs:38)
then somehow its the conversion to the delegate type?
do stacktraces not usually contain some internal unity code
if you do inputs.Add("J", null) instead does the error still happen?
Its normal to start from where unity first invoked it (from native)
Yeah but it should, shouldn't it?
lines 27 and 28 in the original code message (commented to show)
i just did the drag and drop thing once they showed up in inspector
wait they are fuckin null
That's where you declare them
but where do you assign them
wth, does null.Method yield that instead of a NRE?
hmmm possibly yeah
Where do you tell the code which handScripts the variables RFist and LFist hold?
static fields don't show up in the inspector, so you would need to do RFist = something; in code somewhere
Perhaps the attempt to bind with a null ptr causes the exception?
that is definitely a weird error message
yep
TIL
Probably the reference.Method delegates to some internal method which throws ArgumentException if the reference is null
that's super unintuitive
this is exactly what happened, they were showing up in inspector before i made them static because i was getting an error that they were "supposed" to be static, and once i made them static, i forgot to actually assign them in code (bc it didnt work thru inspector anymore)
ah that'll do it
thank you all so much!!
if it were, eg, () => RFist.Punch() it'd be an NRE wouldn't it (but it'd only have the error once it was called)
yay for member function wrappers
how the classes work in c# or unity idk?
you aren't going to get a different answer by crossposting here
A question how to approach my issue the correct/smart way:
I have an item interaciton script where I listen for if my item has dialog and if it has, I want to play the dialog first and when the dialog ends I want to activate my item. What's the best way to approach this? I don't think it's correct o change anything in my dialogue maanager right?
Basically what I'm trying to do with the left picture is to listen wether my item is available & has a dialog, if so enter that if statement.
Then I'm opening the Dialog, here comes the tricky part. How do I tell the game/script to 'wait' here until the dialog ends to then enter the next if statement to then activate my item and disable my interaction icon
Not enough context here
is this running in Update or something?
!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.
How do I tell the game/script to 'wait' here
But in general it sounds like what you want is a coroutine. Coroutines are designed to do exactly this
I thought of something like a Coroutine, but as far as I've used it, it's mainly to pause something for x amount of seconds and not for 'wait until the dialog ended'
You can wait until any condition you want
Or WaitWhile
Or just yield return null in a loop and checking a condition manually
Interessting. This way I can make yield return !dialogue.playing basically
(in case this is abit confusing btw, the yellow is just the syntax you need to use for this specific type of thing, the red is whatever kinda bool/"condition" you wanna use)
just mentioning cuz it trips people up sometimes
yeah I've been struggling with stuff like that unfortunately. Still learning stuff like that
very helpfull guys, thanks a bunch ❤️
It's called a lambda if you want to look it up.
So, what I'd like to know now is, what do the brackets mean?
we basically give in nothing and then we wait until the state reaches its goal?
https://paste.ofcode.org/T76r5XhxykJVm3YHmvKHqR
In my small brain world I would have used it like this
() => 1 is a function that takes no arguments and returns 1
() => frame >= 10 is a function that takes no arguments and tells you if frame is at least 10
It captures the frame variable and retains a reference to it.
You could also write a method like this
bool PrincessRescued() {
return frame >= 10;
}
and then do yield return new WaitUntil(PrincessRescued);
Unity will evaluate that function every frame until it returns true
anonymous functions are convenient for one-off functions that don't need a name
a method is a function that's part of a class or struct
we would say that it's a member of the class or struct
just as fields are
public int x = 123;
fields are member variables; methods are member functions
Woah that's a lot of infos
That's so interessting, but I feel like I'm not there yet to fully understand everything you said. But I'm sure I'll get there
the important part here is that you're creating a function that tells you if you're done
public void Example() {
System.Action<bool> isDone = () => frame >= 10;
frame = 5;
isDone(); // returns false
frame = 15;
isDone(); // returns true
}
As of now I understood the wait that I'm able to use coroutines and also can check if a variable changes its value
And thats a win in my books 😄
ya you dont need to know too much of all that just yet
do i properly udnerstand that you check on frame 5 and on 15. on frame 5 it returns false and on 15 it returns true?
i wouldn't say "on" frame 5 or 15 – that's just a variable; it has no special meaning
But if frame was going up by 1 in each Update loop, then yeah
oh yeah that totally makes sense
Coroutines allow you to suspend a method and come back to it later
thanks for explaining 😄
so you could be checking if a certain number of frames have gone by
Hi i have a small question a made a game and now i want to ad a second level to my game. i did this by making a new scene adding a floor and copying the player from level 1 to level 2 but the movement doesnt seem to work even tho it has the same script. am i doing somthing wrong?
hello, how to get the rect information of the yellow on android keyboards?
well, debug what's going wrong
define "doesn't work"
so first of all when i hit the start button nothing seems to really heapen the screen doesnt pop up of the game starting, second is that when i hit the buttons to move the player doesnt move. and this all works in the first level. + in het debug nothing is showing that could be a problem to the movement
you have to do debugging to see where it's going wrong
I have issue planning. UnlockSystem( static class, which purpose is to save and load small data). It would be very demanding to always load from playerPref. What are options to save data.
Saving using json, binary etc
For a 2d game is disabling game objects when out of view and enabling them when back in view sufficient enough for proper optimization if I have alot of game objects? (I am unsure on how much disabling Game Objects lightens pc workload)
quite an impossible question to answer
do you have perf issues? how much is "a lot" of gameobjects?
Honestly just thinking about the future, currently my game isnt that far for me to have performance issues yet, but I will need to be able to be able to use it on old laptops as well. Also Id say at most around 100-200 game objects could be on the screen
that's quite small, relatively
unless you have a loop of 1000s of iterations in each gameobject, you probably won't have issues
don't optimize prematurely
you're just wasting your effort
if you have issues (or you suspect potential issues), figure out what is actually the culprit with a profiler, rather than just doing stuff and hope it's better
reactivating gameobjects does have a cost ie if you need to reawaken every rigidbody and add every collider back into the physics scene
Okay thank you
Hi everyone, I have a question about hitboxes/colliders. Is there a way to generate a an accurate but performant colliders automatically ?
I'm currently adding capsule colliders for almost each limb
you could write a script that makes them based on the bones if you want
is making a game is just bunch of animation coded to run the game?????? lol
no
oh thats how i look at it
can someone know what it will take to make a game like gta san low quality and stuff like that?? like what pc/laptop will require to make it...
mine is i5 and RTX 3050 , and i think so it is enough for the requirement
A team of 50 or so people
Maybe 30 if you don't need high end graphics
nahh i can do it alone im quick at modeling and other stuff
just need a laptop or pc
thats works faster
GTA: SA was released in 2004 so anything newer than that
will take years to do it
mmm thats eveything new now
i will make a trial game like that and see where it goes from there
well, best of luck for it then👍
3D modeling is like one tiny part of making a game
I see thank you, and is there another way/built-in method using the mesh of the character but symplifying/smoothing it to make it more efficient?
the actual gameplay systems are much harder
for colliders? no
i know will see what i can do for now
you absolutely cannot use mesh colliders for skinned/animated meshes
do u know how much the ram should be?? i think this is the most important part lol
What's the name of the function that returns the value between 0 to 360, adding or substracting 360 ?
I don't have the name of the operation so I can't find it on google
Modulo, %
Mathf.Clamp()?
Ty, that was the name in my language as well actually ^^
I actually coded it whatever
Minimum 8gb ram and 4gb vram
One thing to note though is that x % 360f will give values between -360 and 0 in case x is negative
I think it's bad approach, if read JSON file multiple times. Better would be to make app session data or something like that, which somehow gets accessed
to add: this is because the % operator in c# is remainder, not modulo
you can use Mathf.Repeat instead if you only want positive values
What do you mean by "multiple times" here? If you are going to read every frame, definitely bad. Is there a reason not to make a save & load system which reads the file once at start and holds the data in a class for the duration of the game or something similar? The file would be written to once when the player saves the game or leaves depending which you want. When the game is running, the save system (class or similar) is the way to get the data and modify it and from there the data can be saved later. Preferably the save system should keep track if anything has changed since overwriting a file when nothing has changed can be wasteful
Can anybody tell me why?
I'm trying to add cooldown and the general timer works, but the enemy throws the object no matter what the cool down is at.
the cool down can be at any number, and it will still throw it -- ignoring the check completely.
Put Debug.Log("Cooldown timer: " + throwCooldownTimer); inside the brackets and see what it prints
Basic debugging will tell you what's wrong
I tried, but it's no help
Of course it's help
What did you try
Simply logging the values of all those variables in the if condition will tell you everything you need to know
I literally watched the cooldown in realtime as it was 5 and then went back up as if nothing happened
hi guys can someone help me with this. Im trying to get the 3d obj picked up, but it doesnt seem to work. Can someone help me pls im a beginner in this
That's not debugging
Use a debugger or logs
okay what's the difference from watching everything happen as it goes and debugging
I did use logs
!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.
please send your code correctly, nobody wants to download your .cs files in order to help you
What did you log and what did the logs say when the wrong behavior happened?
also you have 2 more conditionals there, not just the timer, have you verified they are also being set correctly?
I put logs to check:
If THAT specific if() was happening (it was)
If the cooldown was above 0 when it happened (it was)
That's not possible. Did you actually log the value of the cool down variable? Show us the code you had with the logs and what it printed
Ikr. Let me set it up as it was
You need to put a log inside the if and print the current value of each of those variables
well show us 😉
no what
Try this:
Debug.Log($"Entered the if statement. Timer is: {throwCooldownTimer}");```
and then run the game and show us what prints
what's the difference?
it's just more informative. When you do Debug.Log(throwCooldownTimer); it's easy to mix that log up with another one since it's just a contextless number
It's the only Log printed I don't feel like there's any need
- I've kept an eye on the timer in the inspector as well and even when it was above 0 it still threw the object
It's very rare in my experience to only have one log printing in my code
It's the only thing I need right now as it's the only enemy
regardless
can you run it
and tell us what it prints
or show us a screenshot of the console
see this doesn't tell us a lot because it's very possible you're looking at the wrong timer variable or something. The log 100% guarantees us the value of the timer that the code is looking at
that's why logging or the debugger are the most reliable methods of debugging
I wasn't looking at the wrong variable??? it literally changed in real time
I just guarantee you there's no way this is going to print a number larger than 0
we aren't over your shoulder, we don't have a way to confirm what you said.
bugs come up when some incorrect assumption has been made, so it's important to verify all assumptions. we don't know your skill or experience level either, so being thorough here just helps us verify every detail
ᵈᵘⁿⁿᶦⁿᵍ ᵏʳᵘᵍᵉʳ ᵉᶠᶠᵉᶜᵗ
He waited for the cooldown once, but then it completely ignored the cooldown afterwards.
both of those numbers are negative
So the timer is always below 0
it didn't change either
Seems like you're not actually resetting it
I am
So your variable here and whatever else you're looking at are not in sync
📃 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.
how? are you sure you're looking at the right variable?
but the log confirms it's not a problem with this if statement
the problem is elsewhere
It plays the animation and an Animation event calls "ThrowCog" which should reset the cooldown near the end
show the full scirpt please and not with a screenshot
!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.
these little snippets don't have enough context to know what's wrong
Why? this is the main focus
why are you making it difficult to help you
Do you want help or not? I'm telling you this isn't enough information. Why are you fighting us lol
There is no way for us to even confirm this code is running.
i feel like the value not changing between those 2 logs is a solid hint
but that hint is worthless without more context on where and how the value is being changed
Yes it makes it very clear the value is not being reset
In fact that log printed 600 times
So there were 600 "throws" happening
for all we know you might be modifying throwCooldown instead 
yeah we haven't even seen how the timer is implemented
My question was about storing data temporarily. If I have static Save and load, how should I store few bytes to later save?
keep a copy in memory to batch your saves, probably
no constant reading/writing to disk
Serializing to json and writing to disk are like the last two steps in the whole process. There's no need to do that constantly. All your game data can just live in memory until you need to store it on disk
Is that called caching? Or is that wrong?
not really
caching is usually the word for an intermediate, faster form of storage between your application and the main storage system.
I'm just talking about the actual live version of the in-memory game data
Ah. So you’re refering to just modifying the variable that gets exported and not actually export it then.
yes
and when we say "variable" here I'm talking about a class you specially constructed to hold your game data that needs to be saved
Got it.
Still gotta learn what limitations constructors have compared to classes.
Constructors are special functions IN a class that you use to create an instance of that class
they're not... comparable things
Unless you mean structs?
My bad. Yeah i was refering to structs.
And not the new instance with parameters
Constructors allow
...what?
classes and structs can both have constructors if that's what you're saying?
No. That wasn’t what this was about
Just a miss understanding on my part about mixing structs and constructors.
Really? C had it?
yeah
C#'s structs closely match the behavior of C structs
c++ also had classes (but the distinction isn't the same as c# struct vs class)
you could use either one as either a value or a ref/pointer type in c/c++
if you have a struct-type variable, you are literally holding the struct's contents
rather than a class-type variable, where you're merely holding a reference to an object
notably, C++ classes still behave like this
C++ requires you to allocate an object on the heap and then store a pointer to it to get behavior similar to C# classes
(you can also use reference types)
Wait. But c# doesn’t allow type references on structs, right? Also thanks for reminding me that structs are called structs and not constructs because i would’ve probably typed in construct next time that i used it
Structs can contain reference types.
what do you mean by "type references"
Perhaps you're thinking of something else, yeah
Maybe i am. I should probably learn it.
I wonder if you're thinking of this behavior
("type reference" isn't a term used in c#)
you cannot have a reference to a struct
if that's what you mean
a variable for a class is a reference to an instance of the class.
That’s probably it.
A variable for a struct contains the actual data of the struct
does boxing not let you use them like references?
given that boxing can be done on mutable types in c# unlike java or js
Not really, no. You can't have two ifferent boxed references to the same struct
i'm referring to getting a boxed reference and then passing that around
How would that look in practice?
yeah i'm just starting to work out the details in my head and it doesn't work lmao
I mean, you can absolutely take a ref to a variable containing a struct
yeah ref variables
(the collision between "reference type" and "ref" is really annoying)
anyway.... let's not complicate things haha
importantly, this means structs are copied when you pass them around
("ref" here is sharing the variable itself, not the thing it contains)
Got it.
oh so like a ref type in c++?
the & doohickey
yeah (that's a reference type)
at one point I had read most of the C++ standard and could give an extremely pedantic answer about this
but i may have forgor
structs are excellent for values that don't need to be shared, especially short-lived values
classes get allocated on the heap and have to be cleaned up by the garbage collector
for example, Vector3 is a struct
conceptually,
class - some object or entity
struct - some bundle of data
If they’re a single instance. Doesn’t that mean you can just easily reference them from a another script?
you mean a singleton?
what do you mean by "they" in "if they're a single instance"
you're using a lot of vague pronouns
Well. You can have multiple structs. Can’t you just reference them all directly by name and get their variables?
Show a code example of what you mean
that... sounds like the normal usage of structs
More specific. I know that I have store in memory to later store it in storage. But what I should use? Separate class?
Vector3 a = new Vector3(1, 2, 3);
Debug.Log(a.x);
something like that, yeah
I made static class for storing and taking from storage file, but I have to keep taken data to use it until player doesn't needs it.
//Struct
public struct MyStruct
{
public int myStructVariable = 1;
}
//From a monobehavior script
public MyStruct myStruct;
private void Start()
{
myStruct.myStructVariable = 1;
//I was thinking of this but it doesn't work
MyStruct.myStructVariable = 1;
}
MyStruct is the actual type.
types are like a blueprint: they describe the shape of something
myStruct is a variable that contains a MyStruct
it's an object created from the blueprint
myStructVariable is a field – a variable that is a member of an object
you must have a specific instance of MyStruct to do anything with that field
just like in classes, myStructVariable is an instance field, you need an instance of the type to access it
Yes
Yeah thanks for the clarification. I have had some exceptions to this rule where referencing the type was the way to go. I thought it was also the case with here
for instance having a public constant requires you to referencing the name of the class rather then a instance
I think using a class is the better way to go by default you will run into fewer pitfalls
I see. Yeah i just use classes for now.
You just need to remember to construct the instance with new()
yes, fields/methods/props marked const or static are not instance members
anything else is
classes and structs arent' different in this regard at all
Got it.
oh it does actually work
using System;
public class HelloWorld {
public static void Main(string[] args) {
I s = new S() { a = 0 };
I t = s;
t.a = 1;
Console.WriteLine(s.a);
}
}
interface I { int a { get; set; } }
struct S : I { public int a { get; set; } }
Hello everyone!
I just developed a mini Android app and to release it on Google Play, I need a group of 12 testers for 14 days.
I already have 6 testers, so I’m looking for 6 more.
If you can help, please DM me. Thanks a lot! 🙏
you're sharing the object that boxes the struct here
yeah
that's what i was referring to originally
i probably didn't articulate that very well
make a post in #1180170818983051344
How to manage branching levels with requirements, max 20 levels. Should I make for each level id and store them in JSON, if unlocked? When levelmenu scene is loaded read file and enable each level point on map with same level id?
I don't see any problem there. Keep a reference to the data class somewhere available, if you only need one set of saved data, you may also make the class static
But you can't change static variable
you absolutely can, constants you won't
You thinking about data class keeping references to map points and unlocked levels?
in simple words can someone please explain what [SerializeField] means?
It allows a field to be serialized, which includes letting it be edited in the inspector, without having to be public
what does "being serialized" mean?
Sure, store whatever data you need to store
It lets it become a file on disk, which is how the inspector edits it
then whats the benefit of using serializefield? couldnt i just use a public float or public gameobject instead?
You could make everything public but you shouldn't. Generally only the things that you need to access from outside the class itself should be public. The only, but noteworthy, real problem with things being public unnecessarily is how it can allow you to access things that are not meant to be accessed which can cause bugs in your code. [SerializeField] on private field is the better choice when you only want to make the field editeable from the inspector
good to know, thanks!
hey does anyone here have any tips or advice on starting c# coding in unity coming from 4 years of proffesional roblox scripting
theres pins here for C# stuff
as for unity
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
👆 this is your best bet to get started
cool alr
ok but if it asks for my credit card im swiping that shi down my ass cheeks
tmi.
yes but im tryna get started with scripting, i dont want to be copying things from tutorials because then im not learning
Unity learn should have some ultra basic scripting tutorials (using Unity) 
For instance, programming basics (beginner scripting) with Unity https://learn.unity.com/project/5c8920b4edbc2a113b6bc26a
You might want to consider the basic C# programming resources here too. The "self guided" thing is interactive and quite good.
is this outdated or still relevant
The tutorial was for the Unity Version 2019.3 (apparently changeable) but the basic programming concepts and C# language haven't changed.
Ok thanks
You should do the tutorial with a compatible unity version to not have to worry about Unity api integration.
the api is so stable its fine
the only major thing is old input being depricated
Is there a way to turn on safe mode compilation without being in safe mode? This prevents race conditions from multiple agents while the other one can crash
agents? huh?
safe mode is purely to let you fix compile errors before fully loading a project where assets could get mutated incorrectly
yeah but its so nice in safe mode that it never causes problems. But if you work with 4 on the same worktree, it can assembly reload while some are writing and then you have to taskmanager. you can do it manually ofc but savemode has it already solved
What agents are you talking about and why would they "crash"?
Claude, gemini, codex. AI agents. Crash because of race condition compiling and writing. A solution would be worktrees but then you have to git merge
Why would they crash? Or is it unity crashing?
Anyways, having 3 different agents make changes to a codebase sounds crazy...
here are the codes. i dont understand how its now working
!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.
the assembly def with jobs inside are more fragile for that for some reason
That doesn't really answer my question. You keep on speaking in riddles.
Its either an infite loop or crash with crashreport. Its as I said probably a race condition. you want to review what one agent did, while another one is still writing. While, as I said, a solution would be git worktrees, I noticed that the safemode doesnt seem to have that problem. I sometimes like to work on a single branch on a single module but different section of it in parallel to avoid git merges since they know this way more about each other. The job system that uses burst compile (which can be turned on to compile ahead of time in the editor.... I should uncheck it) is more fragile to it.
So thats why I asked the orignial question if I can have always save mode somehow.
Edit: Maybe its just burst compile, I have burstified everything gonna test so nvm
I just asked what exactly crashes, because initially it sounded like the agents crash, and not unity.
I only expected an answer like "unity crashes". That's it. Nothing more, nothing less..
Hello there. I made some changes on my laptop, but noticed this bug that makes the editor unusable, it wont ever load.
I downloaded the changesets on my PC and same thing happens. No idea what causes it, it was just script changes and this window pops up not during the play mode. Is there any fix to it or do I just have to revert the changesets? And maybe do something extra?
I'm guessing it's something you wrote. This might be related:
https://discussions.unity.com/t/editor-stuck-at-unitysynchronization-executetasks/250083
I will look into it, thank you
📃 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.
You need to share a link to the paste site. Not screenshot it. It was specifically to address the screenshotting issue...
OK, great. Now, you need to debug the code. Add logs in all your methods. Or attach the debugger and place breakpoints.
You need to see how far the code executes.
Needless to mention, but you should of course make sure the component is present in the scene and is active/enabled.
nothing i'm doing can possibly make my in-runtime generated objects use a material other than default
i'm doing exactly what others are saying to do
all of them load as Universal Render Pipeline/Unlit regardless
my hexes are invisible when using this material and are fine using the 2D version so i'd like to switch
Can somebody explain, why are we using singleton instead of static class?
they're for different things
are you referring to some specific example?
we aren't psychic
instances are for when you want instances
in minecraft if theres a dungeon it might spawn 3 zombies
you'd want 3 instances of the zombie
most things in games you'd want instances
Singleton not instance, my mistake
two big reasons that come up
- being able to mess with serialized/exposed fields in the editor (so it needs to be a component on a gameobject)
- need a monobehaviour if you want to run coroutines
a lot of my stuff in singleton setups ends up being static
Hi, sorry to bother you, but I have a question. I started using the Localization asset at the beginning of this week, but for the past two days, whenever I reopen the project, half of the things I had done in the Tables are not saved. Do you have any idea why? Just to clarify, I’m not in Play Mode while working and I save continuously.
Is this directly related to coding?
If it's not, you should probably try moving the question to an appropriate channel or #💻┃unity-talk
Make sure to provide pictures and examples to illustrate what's happening and what is expected to happen.
I think so, because I created a script that extracts the text inside the TMPs to then create the key, and I think it might be related — the only thing is that before I close the project, everything works fine…
If you think this isn’t related to coding anyway, I’ll move the chat right away, and thank you in advance.
public void HookMovement()
{
if (isHooking)
{
Vector3 target = grapplingHook.hook.transform.position;
// characterController.Move(distance * 40f * Time.deltaTime);
transform.position = Vector3.MoveTowards(transform.position, target, 40f * Time.deltaTime);
}
}
does anyone know why my character is overshooting the target?
i want him to go exactly where the grappling.hook position is but he goes above it
You might want to log to see if the target is where you're thinking it is. Move towards should not overshoot, according to the docs.
You're teleporting btw by altering position with transform.
Which object is your character? transform, or the CharacterController?
If you're using CC, you'll want to sync the object
You're moving two different objects here it seems
im making a grapplingHook, im now moving the character
i got it working but thanks anyw!
is this some kind of dead by daylight type script?
a dbd fan game?
What makes you think that 🤔
Dbd player learns about hooks
bc ''isHooking''
Grappling hooks.
oh
im sorry
im sorry im not smart into what misinterpretation mean
never played it
this is the game
adding grappling hooks to it basically
nice game
Is there a way to convert a width or height of a rectTransform into worldspace distance? or perhaps directly get a ui elements dimensions in world space measurements?
I'll check that out right away.
how hard/easy would it be to make a modular script that would take a mesh and add 3 bones to it..
making the middle bone be scaleable.. making a script i just add to objects like a stick of dynamite for example..
making it expand before it blows up... like in cartoons
really asking if its possible
i rigged this stick myself.. just curious if there was a code / time saving alternative
Okay, again. This seems to be happening after alt-tabbing the editor. I reverted changesets to before it was happening but it still happens. It won't ever finish, I have to kill the process. Annoying as hell.
what version of Unity?
3 bones should be fairly trivial if its deterministic placement + distance based weighting, but that should also take about 30s per object in blender
I just realized im having 2 log errors in my console related to Unity AI (which im not using), could it be related to the editor freezing?
Error after 1 attempt(s): ApiNoLongerSupported - -- Result type: PointsBalanceResult -- Url: https://generators.ai.unity.com -- Trace Id e6f736fd-c50d-4316-8eec-d7154addc265 =>
UnityEngine.Debug:Log (object)
Unity.AI.Toolkit.Accounts.Services.Core.AccountApi/<Request>d__16`1<AiEditorToolsSdk.Components.Organization.Responses.PointsBalanceResult>:MoveNext () (at ./Library/PackageCache/com.unity.ai.toolkit@5b5621a1dfc7/Modules/Accounts/Services/Core/AccountApi.cs:178)
System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1<AiEditorToolsSdk.Components.Common.Responses.Wrappers.OperationResult`1<AiEditorToolsSdk.Components.Organization.Responses.PointsBalanceResult>>:SetResult (AiEditorToolsSdk.Components.Common.Responses.Wrappers.OperationResult`1<AiEditorToolsSdk.Components.Organization.Responses.PointsBalanceResult>)
AiEditorToolsSdk.Components.Organization.OrganizationComponent/<GetPointsBalance>d__4:MoveNext ()
System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1<AiEditorToolsSdk.Components.Common.Responses.Wrappers.OperationResult`1<AiEditorToolsSdk.Components.Organization.Responses.PointsBalanceResult>>:SetResult (AiEditorToolsSdk.Components.Common.Responses.Wrappers.OperationResult`1<AiEditorToolsSdk.Components.Organization.Responses.PointsBalanceResult>)
AiEditorToolsSdk.Application.InternalServices.SdkOperation.SdkOperationService/<ExecuteRequest>d__4`1<AiEditorToolsSdk.Components.Organization.Responses.PointsBalanceResult>:MoveNext ()
System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1<AiEditorToolsSdk.Components.Common.Responses.Wrappers.OperationResult`1<AiEditorToolsSdk.Components.Organization.Responses.PointsBalanceResult>>:SetResult (AiEditorToolsSdk.Components.Common.Responses.Wrappers.OperationResult`1<AiEditorToolsSdk.Components.Organization.Responses.PointsBalanceResult>)
either update or remove the AI package
Hi, I'm learning from scratch and following the tutorial I'm watching. Everything seems the same at first, but my controls aren't working correctly: W doesn't advance, A moves sideways, etc. I don't know what the problem is. If anyone could tell me, thank you very much.
Then the first thing you should learn for this server is !code
Which ones of these? I have to remove them in manifest since the editor freezes. All? Or is the last one the agent system?
"com.unity.ai.assistant": "1.5.0-pre.1",
"com.unity.ai.generators": "1.0.0-pre.20",
"com.unity.ai.inference": "2.4.1",
"com.unity.ai.navigation": "2.0.9",
!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.
I think the last one is navmesh related, but not 100% sure
Yeah I think so too. Ill remove the first 3
I would assume your movespeed is 0
its 5
I followed all the steps in the video and it's still not working.
https://paste.ofcode.org/3GiJJF3vPSPu65icgsbFJL this is AI output so take with a grain of salt but it should atleast give you an idea of what to do
i wuld only use it. or typically use it on small singular objects..
cylinders, spheres, cubes.. etc.. but it'd always be just to inflate the object..
1 bone in the middle to scale.. and 2 bones on the outside for anchors or w/e ud call em
thanks friend
yeah thats exactly what this script is made to do
awesome.. i code all my stuff into utility classes.. so i'll check it out and get the gist of it.. and rewrite something myself 👍
thanks for takin the time @silk night 🧡 🙏
-# man i'm so used to you being purple, i keep not recognizing you lmao
-# the roles are irritating.. (i wanted just asset publisher bt it forced me to addanother)
thank my companies codex subscription, I just sent a prompt and code reviewed 😄
lol.. i'll start thanking robots when im forced to 😅
😄
I am pretty hesitant with AI stuff but usually let it generate stuff like this and make my own script out of it, just to get an idea how to start on stuff I have no idea about (like creating bones out of thin air)
better? 🙂
char cant rotate, why
i mean, how you had it wasn't bad, i just wasn't used to it
!code share code properly please
📃 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.
lol.. all good i can't get teh asset publisher color to be the primary.. sooo im not worried what color i am lol
hello guys, Is there anyone that's bored enough to help me do a little 2d project in unity? I am new and don't know much but I have an assignment
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
no-one's gonna want to help without any info whatsoever lol
booooring
that's the thing I kinda have to start from scratch
I CANT SHARE CODE???
did you try to send it in my dms for some reason
its in the server
Ah god dammit. I removed AI related packages from manifest, removed library folder, deleted packages-lock and AI packages are still in my project and I cant remove them. It breaks my entire projects in endless loadings.
hello
this is a code channel, try #💻┃unity-talk
// normalise input direction
Vector3 inputDirection = new Vector3(_input.move.x, 0.0f, _input.move.y).normalized;
// note: Vector2's != operator uses approximation so is not floating point error prone, and is cheaper than magnitude
// if there is a move input rotate player when the player is moving
if (_input.move != Vector2.zero)
{
_targetRotation = Mathf.Atan2(inputDirection.x, inputDirection.z) * Mathf.Rad2Deg + _mainCamera.transform.eulerAngles.y;
float rotation = Mathf.SmoothDampAngle(transform.eulerAngles.y, _targetRotation, ref _rotationVelocity, RotationSmoothTime);
// rotate to face input direction relative to camera position
transform.rotation = Quaternion.Euler(0.0f, rotation, 0.0f);
}
Vector3 targetDirection = Quaternion.Euler(0.0f, _targetRotation, 0.0f) * Vector3.forward;
// move the player
_controller.Move(targetDirection.normalized * (_speed * Time.deltaTime) + new Vector3(0.0f, _verticalVelocity, 0.0f) * Time.deltaTime);
char doesnt rotate
i didn't read particularly well in #🏃┃animation and i'm not super familiar with moving via animation; was the issue not related to animation config?
no
alright, do some debugging then - is the rotation code reached? what value you are setting?
also, you should not read back the value of transform.eulerAngles, you should track that value yourself
also, Atan2 takes (y, x), not (x, y)
For learning to code would you guys recommend
1: Taking notes while listening
2: No notes just apply what you listen to with an editor
3: both
4: neither (something else)
it probably varies based on the person, but what do you guys recommend
I try to avoid triginometry in general, haha
whatever works for you
try them out and see what works for you
Quaternion.AngleAxis(dir, Vector3.up); spits out a rotation that points in the direction of dir
oh that definitely would help yeah
Vector3.SignedAngle tells you the angle between two vectors
(given a third vector to figure out whether it's a positive or negative rotation)
(though Atan2 in particular is a very conceptually simple operation imo)
yeah, I just haven't had to use it in ages
the rotation variable is working
the euler thing isnt workin g
i want it to rotate to move direction only...
are the values for _targetRotation correct?
ill see
well, are those the angles you expect?
I wonder if you're rotating the wrong object
its the player char
This is going to rotate the object that the script is attached to
its attached to player, aand i dont see any rotation
Disable the script and manually rotate the player
(in Play mode -- not in Edit mode)
does the player rotate as expected?
Also, is there an Animator involved? If so, show me your hierarchy
(and even if there isn't, do that anyway)
I'm wondering if you are trying to rotate an object with a SkinnedMeshRenderer on it
i'll be interested in which object this script is attached to
here
Okay, that should be fine.
Try this next.
When you're getting weird behavior, you want to start ruling things out
lol as soon as i turned it back, the plr snapped back
Okay, so something else is rotating the player
I don't think animators can affect their own object's position
it was working fine before... all i did was remove jump functions and this bug came
oh, they totally can
How did you do this?
i searched in the script "jump" and removed all lines that enabled jump functions
i also removed jump functions
hm, that doesn't sound like the cause
So you disabled the Third Person Controller script and the rotation is snapping back when you let go?
Turn off the Animator as well.
really, just keep turning things off until you can rotate the player object properly
when i re enable it
ill try
oh, okay, so you can freely rotate the player while the component is disabled?
in scene mode
not game mode
when i enable it and try to rotate manually, it doesnt rotate
by "enable it", do you mean going into play mode?
i'm guessing the script has [ExecuteAlways] or [ExecuteInEditMode] at the top, then
no
and you are not in Play Mode?
in play mode
- enabling = snapping
in edit mode - rotating char then enter play mode, snap at the same old direction
okay, that's expected behavior
This means that no other script is trying to rotate the player
Make sure that you aren't setting the player's rotation anywhere else in the third person controller script
no way
i disabled all transform.rotation and it still snaps lol
i have 2 transf rotation idk why that
note that you could also be setting transform.forward
(or up/right)
if you can't find anything, share your whole script with one of these sites
i enabled this and its useless
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(inputDirection), RotationSmoothTime);
!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.
i made a first person camera script and it works well but for some reason when moving and turning, theres a lot of jitter. does anyone know a fix? https://paste.ofcode.org/DxKXK2rYE3EcnjxdfMGm5
does this object or the parent have an RB or CC?
the parent has a rb
you shouldn't be modifying its transform then - the rb will try to control the transform
use the rb to rotate
okay, ill try that out, thanks!
for unity coding, would you pretty much only use float, int, string, bool, List<T>
or are things like double, decimal, char also sometimes needed
for variables
yes, you use what's needed for the thing being done
it depends on what you need
higher-precision data types (like double) should be used if your game requires the precision
hey, mb dump question, but: how work Time.time? is it global time wich work with real world time or it count frames? Where i can use it? bc i think Time.deltaTime and courutine do all better then Time.time
Have you read this yet?
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Time-time.html
I know this ins't a code but there's a portuguese chat or server?
Is difficult for me communicate in inglish and i cant find one
English* for a start ;p
Programming is a great way to learn English though since everything will be in English. My English was much worse than yours when I started learning Unity. Watching a lot of Unity videos and tutorials, reading discussions and documentations online and conversing in help servers like this one pretty much got me where I am now with my English skills. Don't be afraid to ask anything you need help with. Most here aren't native in English either, perfection isn't required to be understood. Good luck
Hey, I'm currently learning to program on unity with zero knowledge
I already did some tutorial to understand how the app work and now I'm trying to do very small game project and asking chat gtp about how I could improve my code or how I could achieve something (I still try to think how I would do it personally so It doesn't feel like chat gtp is programing everything for me)
Tho it does make me wonder if there would be a better way to start my programing journey, does anybody have ideas or a good bot/ai made for programing that I could ask my basic question about ?
Guess how we all learnt before llms came along a few years ago? There are plenty of tutorials for unity and c# in general.
https://learn.unity.com/pathway/junior-programmer
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
I did already knew about unity learn, and learn the super basic from there,
I was curious about starting another lesson about creating some basic games, but there is so much to look at those days that I didn't really knew what to pick and really wanted to do that one lil game I got in mind to train my self
If you think this would still be one of the best tutorials to follow I'll do it, was just exploring my option
Mb if that was a dumb question ^^;
Unity also offer a few game courses so either try those or some game tutorial series on youtube
https://learn.unity.com/course/3d-stealth-game-haunted-house
Welcome to this revamped version of the beloved John Lemon game. We know how much this project means to many of you, so we made it even better! This time, John Lemon isn’t the only one sneaking through the shadows. Ivan von Vamp, a tiny vampire with a big personality, is also ready to embark on the adventure and escape the haunted mansion full...
Alr thanks, I'll look them up, I appreciate the quick help ^^
hi everyone, quick question
i'm working on a basic dialogue system for my games lobby area, and it is fully working; but when i rotate the npc the direction of the text gets all messed up (first npc in the video is with 0 rotation, second one is rotated 180)
for context, i use individual gameobjects for each letter, so that i can have them scale up, and drop down
i spawn them in, inside a foreach loop that goes through all the char's of my dialogue string
GameObject temp = Instantiate(dialogueLetter, letterStartPos.position + (letterStartPos.right * (letterX * letterScale)) - new Vector3(0, lineDistance * letterY, 0), letterStartPos.rotation);
i use the right direction of the start position, as a reference, and the right direction points in the correct direction in the editor, if i check it with local editing, so i have no idea why it's moving the incorrect direction
would love some help cus i'm completely lost
the setup you're showing is incomplete,
do you mean that i should show more? cus i thought this would be enough, since this is the only line that actually does anything with the position of the letters
i can send the full bit if needed
anything helps, where exactly does the startPos end up when you rotate npc, do you do any parenting etc.
inspect the game with the scene view side by side game view and see whats happening , slow or step through the loop if you must
but if you rotate 180 it kinda makes sense its flipped cause your right of enemy may not be your right of cam
the start position is parented inside a worldspace canvas, that is under the camera, and the camera is under the root of the npc, so it's right direction shouldn't change (and when running the game and checking the scene view, the right direction is still pointing where it should be pointing)
i parent the letters under the startpos after they are done being set up, but that shouldn't change anything since by then they are already positioned (i also already tried positioning them after the SetParent, the result was the same)
also here is the full foreach that does the spawning (the ''star" is what i use as a new line marker, cus it's easier than doing multy char samplings for \n)
foreach(char c in dialogue.dialogueText){
PlayAudioChar(dialogue.dialogueTextAudio[iter]);
iter++;
if(c == 'star'){
letterX = 0;
letterY++;
}else{
GameObject temp = Instantiate(dialogueLetter, (letterStartPos.position + (letterStartPos.right * (letterX * letterScale))) - new Vector3(0, lineDistance * letterY, 0), letterStartPos.rotation);
temp.transform.SetParent(letterStartPos, false);
lettersGen.Add(temp.GetComponent<DialogueLetter>().SetMeUp(c));
letterX++;
if(letterX >= lettersPerLine){
letterX = 0;
letterY++;
}
}
yield return new WaitForSeconds(timeBetweenChars);
}
(ignore the star thingie, it broke the code display so i replaced the star char with the word)
i mean yea, but i use the .right of a transform, that is under the camera, which should, and does point to the right of the camera setup
how are you setting letterStartPos? and does letterStartPos.rotation have the values you expect?
it's a transform set in the editor (in the screenshots, it is the object i have selected), and in the sceneview, it's right direction is correct even while spawning the letters
oh so .right of cam not the NPC ..
the .right of the letterStartPos, which is under the camera so it should turn it's right direction when i turn the camera
okay, so i tried doing some tests to see if maybe i can find something, and it seems like the directions of the transform get fully inverted
i tried offsetting the letters using the .forward instead, and they move backwards not forwards (again, this only happens when i rotate the setup)
are you changing letter scale anywhere?
How do I calculate the formula for the bullet trajectory?
And why do people have that formula?
i have a component for the letters, that animates their scale, and handles their drop animation, but that shouldn't really change anything, since i use a consistent transforms .right for the positions, that i never move, never rotate, and never change the scale of
Hello i have a question , when making a 2d platformer how do you manage having a character that is different in size, should all the sliced sprite boundaries be exactly the same, is it possible to do this?
send full code, use paste linnk site 👇
!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.
i ended up doing a small workaround, so it works now tho i still have 0 clue why this even happened ;-;
thanks for trying to help out c:
I cant find a proper place to start on makeing an "Atmosphere" shader.
Ive seen videos on the subject that are really advanced but i want to make a simple "Sky color fades out the further a point is from the center".
Then i can multiply it by the dot product of the suns position to only have it render on one side.
Picture is me mimicking what i want using transparent spheres, but anyone have thoughts on this?
this is a code channel, check out #1390346776804069396 for shader stuff
I figured coding shaders was included but ill check that out
nah this is for scripting/c#
I want to ask a question about unity using all of my 32gb ram while on the frame debugger.
Where to ask?
i'd prob make a static class for this
since everyone seems to be speaking the same way
this way you just activate the dialogue with the character data in it
there's no parenting, no need for everyone to have a dialogue prefab
and its clean
I'm trying to make a reference int field in a class so that the class can modify that int variable directly without caring where it came from. However, it seems C# isn't letting me do that telling me I have to upgrade to C# 11 or something (which I'm also told isn't supported by Unity). So how do I go about doing something like this?
It works just fine when it's a fresh ref int declared in the function, but naturally I want a class that can hold onto that reference. I just don't know how I'm supposed to go about doing that. Pointers maybe? But I'm a bit scared to use them since I'm told they're unsafe and the location of the data can't actually be guaranteed anyway
what are you exactly trying to do here? if you have a reference to some instance of RefTestClass, then it's always going to be modifying the same instance of int resource here
Oh I mean internally. Internally I want the class to modify resource and have it be the variable it was given at initialization with the same changes made to it being applied to the same variable given during initialization
this doesn't sound like something you should want to do
The idea is that it's a command in a JRPG and resource is supposed to be what ever stat is being used as a resource for the command. However, that resource could come from not just any character, but from a select range of stats. It could even come from an item stock. I don't want that distinction to matter, though. At the end of the day anything that should be fed here should be an int and its job is to deduct and/or add to that amount when it is asked to do so
you should probably make some interface or event instead then. Like if you store a reference to an interface and expose some setter method, you'll get the same effect
what you're thinking of currently just sounds like a nightmare to debug, if it is even possible
That would work if I wanted to just erase the distinction between a stat block and a consumable, but runs into another problem. A consumable only has one variable that can potentially be modified by the interface, but the stat block has like 3. The only solution I can think of to this is to put in a flag for the purpose of the statblock's implementation of the interface, but that flag is completely meaningless for the consumable's implementation
truthfully I don't see the point of anything related to the sample code above. This is basically asking how to externally modify values without a reference to the class
Like what purpose does this other class serve that it's being used to update a bunch of random numbers? There must be somewhere else that calls upon this other class to notify it to update. Move that logic to your consumables/stats instead
It also stores the logic needed to actually perform the action, the name of the action, and targets of the action (Because the action needs a source and a list of targets). Ideally it would also store the cost of the action and the resource that cost is connected to
I just simplified a class to just this problem because I wanted a solution to this problem
I didn't want people asking what all the other variables did when it doesn't matter
its also hard to say much given the current context because its just really something you shouldn't be doing. like I cant comment on how you would need to change the other logic to accomodate for this, I don't see what a consumable or stat block is
maybe the solution here is really simple
StatBlock is any information pertaining to combatants that is relevant to that particular instance of battle and is intended to be compiled at the start of the battle then discarded at the end.
a different way would just be to make a new wrapper class with the int you want, so you can pass that class around as a reference instead
which is essentially what you're trying to do with this ref int thing
That's what this is. But I need it to actually be able to modify the ref int it's given just not right now
I need it stored somewhere and C# is not letting me do that
thats exactly what storing it in a class would do, you pass a reference to an entirely new class whos purpose is to hold an int
ignore ref entirely here, it wouldnt be needed
No, it is, because it needs to actually modify the value of what ever variable was passed into it. Not just a clone with the same value
And, as far as I've been able to test, if I just have a regular int as the field and assign it to the ref int it will simply copy the value. Any modification of that field will have no actual effect on the ref int that was passed in which defeats the whole point
I know I can do
ref int resource = ref inResource
But naturally then resource will only last as long as the initializer is running. I don't want that. I want it stored for later modification
you're confusing yourself way too hard here
it isn't needed in the slightest
https://dotnetfiddle.net/7IBTEB
i think technically a ref struct would immediately solve the one case you've shown, but Im like 90% confident you wouldn't be able to use it in the way you want
nvm I think this was only possible in later c# versions like you said above
it has limitations around how you can use it
You probably want this to be a whole class anyway later down the line incase you ever wanna do other stuff with it eg. perhaps associate front end stuff like text or ui or an event like i think bawsi suggested aswell(?)
Just box the integer with a class to make it a reference type?
like in this code your doing string based conditionals to handle this kinda ui stuff and whatnot
when you could bake this into the value class itself
(ive done something like ScriptableStat esque stuff in the past)
So you're saying that if I had a class
{
public readonly Action<StatBlock, List<StatBlock>> action;
protected TargetTag targetTag;
event Action<ActionInfo> onCompletion;
int resource;
int cost;
//I should see if the equal operator takes the reference of the variable, too
public ActionInfo(string name, ref int inResource, int cost, Action<StatBlock, List<StatBlock>> action, TargetTag targetTag) : base(name)
{
this.action = action;
this.targetTag = targetTag;
this.resource = inResource;
this.cost = cost;
}
public void DeductCost()
{
resource -= cost;
}
}```
And tried to run this code outside of the class
```ActionInfo ultima = new ActionInfo("Ultima", ref cloud.currentMP, 80, SpellEffects.Ultima, TargetTag.Party);
ultima.DeductCost();
print(cloud.currentMP)```
That cloud.currentMP will be 80 less than it was before doing all of this? Or will it just be resource that is 80 less with cloud.currentMP being completely unaffected?
im not sure if you actually went through the code I sent above, i dont use ref anywhere
I'm not sure what that means
i sent you an example with exactly that. they are suggesting the same thing I wrote above
You'll only copy the value of the integer for resource and cost as they're primitives
i dont even think this would compile unless im missing something
cause of the ref alone
It's telling me right now that it can run this without errors
It simply won't do anything because it's resource being modified and not currentMP
I want resource to work as a pointer to currentMP, but I'm not really sure if I even should be using pointers for this
class StatValue
{
public int Value { get; private set; }
}
//eg. some thing that has a ref to whatever stat you want
private void ModifyStat(StatValue stat, int value)
{
stat.Value += value;
}
similar to bawsi's just even more reduced
Well.. you're not assigning anything to inResource so it doesn't need to have the ref modifier
Will this actually work?
why wouldn't it
Yes I am. Look at the second block of code
Oh wait I forgot to put ref
did you even open the link i sent above?
i literally showed a full example of this working
int's are not naturally reference based, classes are
so just have an int in a class
just focus on this. you're confusing yourself WAY too hard with ref here
you do not need ref anywhere here
(cuz the class is your ref)
As in a class that is literally just an int and basically nothing else?
You'll probably naturally realise you can put a lot in that class
but in that example yes
resource will not be referring to the memory address of inResource. The integer will simply copy the value of inResource.
I guess I can try it
🤦♂️ i dont think i can help if you aren't gonna actually go through the example which proves the entire thing you're asking about
if you were confused about the code sample i sent, then ask something. we shouldnt need 3 people to tell you the exact same thing
Right. That is the problem I keep running into. If just putting a class around it fixes this then I can try that, though.
How do I turn off the VS autocomplete?
It's trying a bit too hard to be smart and won't stop replacing my var with ShaderVariantCollection
Somewhere in the settings. Ai assisted auto complete.
actually it may be regular VS autocomplete and not AI
var wouldn't work anyway since I was in global
but I would've seen the red squiggle earlier if it didn't keep forcing the suggestion
scroll up to the top, select 'var' .. I think it'll eventually stop suggesting that shadervar..
You don't want to turn intellisens off, you'll have to remember everything
All I need from intellicode is the usage information you can find in the regular docs ngl
I'd rather not have to keep going to the docs for spellings, or lists of available functions/ properties for things I already know but can't remember.. 🤷♂️
Having to type code out completely would be a nightmare
It's just comfier for me to not have something try to autocomplete what I'm tryna do
(intellicode and intellisense aren't the same thing btw)
Hi guys hope you all are good and alright, so i was planning to practice my programming skills by creating different systems in unity so can you guys suggest me some systems like quest system etc etc that i should try developing from scratch which would help me be comfortable programming stuff that is entirely new for me!!
make something you want to make
i always wanted to make a robust quest system where i dont have to do some hard coded callings, should work in a way that i just import it in any of my game and i can use it, but the thing i suck at is how should i plan this all, should i just go with the hit and trial approach(i am trying not to use AI for starting, cuz that would eventually affect my judgement to solve problems)
start designing the system on paper (or in a diagramming tool or whatever you're comfortable with) before considering the implementation
got it thx!!!!
Start simple and small first
Take your concept, abstract it to its simplest form
Break that down into individual problems and go from there
true, intellicode is the dumber version or something before intellisense came out if I remember right?
no, intellisense is the autocomplete box and hover info, intellicode is the gray ai generated stuff
intellisense is a normal feature that's generally very useful
yeah I see now xp
that looks like a 3d collider, that wouldn't collide with 2d colliders
haven't we been over this
The green sphere is the particle collision shape/bounds
What is the question though? Like what is the screenshot supposed to show, the colliders are not visible
is it possible that i can make the particle system 2d
all my other colliders are in 2d 💀
my game in 2d
It is 2D. There's no 3D collider in that screenshot, Chris mistook the green sphere for a 3D collider
O_O
The whole point of the Triggers list being of type "Component" is that you can assign both Collider and Collider2D to it
is it not then? i don't have any experience with the particle system, but docs seem to say it's a collider shape
i may have misinterpreted them though
then wot in god's name is happening?
But it's effectively 2D if you're using 2D triggers in the list
(well not a collider since it's not the same color, but i assumed it was using collider shapes under the hood)
I have no idea what you are actually asking originally
anyone know why it On particle trigger gets called iff outside is set to callback?
🤔
here
check out the log and you will understand
i genuinly don't understand how people did unity before unity discord became a thing
So it is triggering the callback when you dont want?
it only triggers callback on outside
Seriously, don't assume that people understand what you mean just from a couple of videos with multiple things happening.
Prefer text explanations
And what do you expect?
i expect it to do that when enemy collider is inside the particle, but that's not the only problem. Even if I were to increase the radius of this trigger's radius scale field to a very high amount, it still triggers the callback even though the enemy collider should be inside this radius, and not outside of it
Why do you expect the "outside" callback to fire when it is inside?
nothing
if only outside has callback and everything else has ignore, callback should not happen when enemy collider is inside, entering, exiting this radius
it is happening
i don't expect it to
i expect it to do that when enemy collider is inside the particle
Very contradictory but okay
Are you sure it’s the enemy triggering that? Those logs don’t confirm that
wait, let me explain what I want, and what i am seeing in one full elaborate explanation
-# this was expected of you from the start, man
The docs don't state if the particle needs to be inside/outside of all or any of the colliders
So that might be related
What I want:-
- If enemy collider is outside particle, don't do anything.
- If enemy collider entered particle or is inside particle, trigger
OnParticleTrigger
To achieve this, I set Enter and 'Insideto Callback, and rest to Ignore
What I observed, nothing was triggered.
So I started tinkering with the various things and found out the following:-
- Iff I set
OutsidetoCallback, does any form of triggering ever happen, in any other scenario, whereOutsidehas been set toIgnore, nothing gets triggered
i thought u guys would understand from the videos, mb
Did you use OnTriggerStay/OnTriggerEnter or OnParticleTrigger?
Because the OnTrigger stuff isn't used by particle systems
changed it
Right, I see your edit
void OnParticleTrigger()
{
Debug.Log("Particle Trigger Detected.");
}
Bump
we are not in fact psychic
I believe the particle system only checks the colliders that are in its triggers list
So it would have to be either of the Duck colliders
@tired python So when the Enter/Inside callback did not work, were the particles inside both of those colliders or no?
I'm not sure if it requires all or any
am i dumb why are the game view and scene view different here
(In any case - I avoid using particle collisions for gameplay logic and treat them as purely visual components)
Scene view is from behind
wouldn't that be really hard to code for complicated particle systems?
Well no, just some physics queries like raycast/overlapcircle etc.
Ofc it is harder than just enabling a checkbox in the particle system
But at least I know what's going on :p
Is your particle system at zero Z position?
well poop
the goddamn spline is set in the same xy plane, how the hell does z happen to change
z is changing everytime the duck moves
Select the individual spline knots and make sure they have a Z position of zero
excuse me?
If they're in Bezier mode, also make sure that both handles are at Z=0
I would expect Z to not matter in 2D but maybe there's some quirks with particle system since it uses both 2D and 3D collisions
how do i do that
turn on the spline edit tool
then click on the spline knots and make sure the handles are flat
(you may want to leave 2D mode to view this)
2D collision can use the Z-axis. I have no clue what particle systems do, though
When does 2D collision use Z?
when you tell it to, afaik
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Physics2D.Raycast.html
Ah yeah that!
this thing?
That’s the erosion of the knot itself. I believe that does mean that the handles are sticking straight out on the XY plane, though
So that’s correct
some of them are reverting back...
"Reverting back"?
i manually set it to 0, then i select another knot and then i select the same knot once again, and i see it have a value other than 0
like this
hm, I'm not sure – the rotations might be getting affected by the neighboring knots
I'd start by getting the knots rotated correctly
notice how they're at a 90 degree angle to the 2D plane
yes
I think you can just give them a Y rotation of zero to flatten them out