#💻┃code-beginner
1 messages · Page 619 of 1
but you could also just make a struct that holds your values and make a list of that
to tbh you can easily just make a List and custom struct
lmao
jinx
idk
sounds hard
really isn't
nah its easy
i dont really know how structs work
same as a class
do you know how classes work?
you use structs all the time
structs are classes but a little different
Vector3 is a struct
oh
float is a struct
they are like value types
yeah
its just for grouping fields and methods togther
is that the only difference?
value types and structs are synonymous in c#
yea they live on the stack usually
ohhhhh i didnt know that
ye this is were you lose me XD
well i mean, only when they're local
dw about that part rn its just how its handled in the back end
yes
heap stores the address to the location
ohhhhh
reference types
values of reference types are stored as references to the actual object, that's on the heap
values of value types are stored as the value directly
ah okay
ofc you can do this with a class too..
ye
i honestly prefer when working with reference types but thats just preference
local variables are on the stack, so if you have a local variable with a value type, the struct value is directly on the stack
but idk how i make it serializable
also i would have to use linq to filter or what?
you slap a [Serializable] on it
Fixed yet?
no im working on it
but i mean if anormal dictionary works why cant i just use that?
Damn.. alright ping if you need help
i mean im getting helped rn
https://docs.unity3d.com/6000.0/Documentation/Manual/script-serialization-rules.html
see this @fleet venture
unity doesn't know how to serialize it
Yes but for the past hour or so xD
so the idea is
public struct CustomProp {
public string Name;
public Prop TheProp; ```
but i dont need to access it in the editor
only the editor script needs to assign permanent values
oh...ok
idk if it has to be serializable for that
i don't know your original issue lol, i was going with what nav said lol
it could make it easier for sake of serializing into files
or showing / configuring future props in the inspector
so always good to use Serializable
ye but a dctionary is easier to work with than this isnt it
cuz like that you have to use linq to filter which doesnt sound like its super ncie
you dont have to use Linq
No. Custom serializable classes are easier to work with in Unity
you can override your own == and all that
i mean i would want to have []
or Contains
like, to index by key?
like how dictionaries work
It’s just dictionaries aren’t serializable by default
oh
that returns a bool though, rather than the full entry or value
my b just meant finding by object in general not Contains
pass the object but it looks for the name via string
ye i do
is it possible to do like an operator overload in the struct though so i can just use [] like a dictionary?
because this is LINQ right?
it looks like it
oh
i thought it was on IEnumerable or whatever
hold up is === a thing in c#
nah this is too specific for linq
no, sorry im used to js lmao
didn't even notice that
btw, aren't fields usually camelCase
idk unity uses stupid naming
its diff from c#
and it confuses the hell out of me
c# uses stupid naming hto
java has a good naming scheme
C# is like
yeah but this is the case like, everywhere
ok lets just make EVERYTHING PascalCase cuz why not
thats because instanceId is a enum
this is what i hate about the naming in c# its impossible to tell what something is by the name
classes are pascal case, properties are pascal case, public fields are pasdcal case, methods are pascal case, constants are pascal case
like STOP
its so stupid
i mean.. c# differentiates between interfaces and classes/enums...
not sure it's a very useful thing though
public fields aren't pascal case
fields too i thought
either way you should be making it a prop if its public
they are, but also they shouldn't exist too so 🤷♂️
ah nah this is in a struct
or... should those be properties..?
I still make them pascal
doesn't matter, structs should still use properties for things that are public facing
damn
but yeah if you gotta do it "correct" general opinion is to just use props
good lord
no but it has to be serializable by unity
does Prop have a name or something?
thats what the backing field serializefield is for
if it is accessible outside of the object it should be a property so you can have fine control over how it is accessed and what happens when it is
[field: SerializeField] get; private set; is my default bread and butter
unpopular opinion, people are excessive with encapsulation
that can work too. just makes an ugly backing field name for it @sour fulcrum
ye
you could do theDictList.Add(new CustomProp() { Name = obj.Name, Prop = obj }); i think?
no i want to put all of these props in Room which is in the scene
i don't remember the exact syntax there
idk how i get a reference to Room tho
ok how are you gonna key them though
so.. they do have names
why did you say no then lol
I do not see it 😄
outta sight , outta mind 
anyways this. syntax might be a bit wrong though, i don't remember
Got enough perceivable problems anyway
might need semis
the issue is how do i get theDictList
looks fine
you make it..?
you need to have it somewhere
no theDictList is located on the Room script in my scene
(and name it better)
idk how i get it in the editor script
ah that's what you meant
making accessible through a Singleton or something
depends what needs access to it
Singletons are very good if you have DDOLs and stuff
cross scene references etc
i dont rly want to change it everywhere
ye but this isnt a cross scene reference
its only used in the same scene
and i need to access it in the editor script
as long as you have a reference linked then wahts the problem
how do i get it in the editor script
the one from the scene?
Ideally even just have 1 gamemanager singleton and when your thing wakes up tell the gamemanager about it, so other scripts can access it via the gamemanager
yes
i have a Room inthe scene that i need to access in the editor script
thats my question
where is you editor script at the moment
oh.. I thought you were doing the Menu Item thing
using an editor script is less confusing?
i thought that was the same thing honestly
no
i just have this
MenuItem lives on a MB
usually
it just makes it so it appears above your toolbar menu
where you see File,Edit, Tools, Help etc.
when you want to do stuff from a gameobject you need it to be MB to be attached
You want to toss this stuff in this same script, all your doing is using MenuItem so you dont have to drag them all..
inside of the ROom Class?
though frankly you can just Mass select them and drop them in
no because i also need to put all the keys which are strings
and i would have to put 300 strings in myself
for the names
You just loop through the items in the inspector , the process is the same
i am pretty lost as to what to do and where im at. How do i do the menu item thing
because apparently thats different from what im doing rn
oh i can run it like this if its a menu itme
[serializefield] private Prop[] props; //drag n drop
then do
foreach(var prop in props){
if(prop.name.Contains("barrel")
barrelsList.Add(prop)
obv not real code but just the idea of it
or you need a nasty switch
ye but i need it to stay if i stop running it
yes or you can also use [ContextMenu] which just lets your right click the script to run a function
thats why you run the setup in the editor
unless you had like Enums for each Prop type, you have no choice but to check their name contains a specific thing to group them
my question still stands tho how do i get this instance field prefabs in the static fill method
you can use a scriptable object (singleton)
the grouping in the assets directories isnt important
ScriptableObject singletons are super common in Unity -- especially for editor functionality or general configs
wdym just access it like any other method
primarily because while you may choose to use it as a singleton, you may also opt to replace it with something else for whatever tests you might have in mind
would this work?
[CreateAssetMenu]
public class RoomGenConfig : ScriptableObject {
// your fields
public static RoomGenConfig instance { get; private set; }
[RuntimeInitializeOnLoadMethod] static void Init() => instance = Resources.Load<RoomGenConfig>("RoomGenConfig");
}
[MenuItem("fill")]
public static void Fill()
{
var objects = FindObjectsByType<Prop>(FindObjectsSortMode.InstanceID);
var room = FindFirstObjectByType<Room>();
foreach (var obj in objects)
{
room.prefabs.Add(new PropKeyValue() {name = obj.name, prop = obj});
}
}```
would this work?
huh
thing is i use it in a lot of places
objects are in assets, room is in scene btw
is that an issue? you'd just have to use RoomGenConfig.instance to access it anywhere
ye thats a lot of changes
kind of a pain
all to run this script 1 time
should work fine
wait.. why are you adding to the same object..
you'd have done it 30-45 times in this 90 minutes you've been discussing about alternatives 😛
wdym adding to the same object?
FindObjectsByType searches in both assets AND scene?
oh nvm didnt see the Room part for some reason
so how do i get all the prefabs then?
I been saying use the inspecttor drag n drop but if you refuse to do that, use the method to find AssetDatabase
no i dont refuse to do that
i just do not understand
how
where do i drag it too
You grab them ALL , CTRL + A
and in the same field of that editor script List<Props>
dont make the function static
oh i dont?
uh it doesnt like that
i dont have an editor script
i have the menuitem thign
i changed it like you said
dont use Menu Item
WHAT
just use ContextMenu
with static you cannot use fields from same class
so now i create a new thing
replace the attribute from MenuItem to
[ContextMenu("MyCoolFunction")]
then right click component on gameobject, in the editor to run it
remove the Find part
ye i did remove that
omg ty it worked
thats great
this was so easy how was this so hard
this was 8 lines of code 💀
T-T
probably a mix of misunderstandings lol
most definetly
is there a better way for two script components of mine to reference the same script? Right now I have an audio manager script, but I also have a movement script that needs to reference it to play the movement sounds, and my collision handler script also accesses it to handle collision sounds, basically I just have them both get the component on start
GetComponent on Awake() is the optimal method
thanks
np
what is the difference between start and awake?
one is for initialization and the other for access , generally
Start for example cannot run if disabled script, Awake doesnt have disabling cause it will run as soon as object is active
Awake -> as soon as the object is instantiated
Start -> Right before the first time it enters the update loop
Also start may or may not be called on the same frame so take that into account
gotcha, thanks guys
I clicked "enable Debugging" on this and now it has that setting everytime i press "attach to unity". how do i disable this setting?
"Enable Debugging for All Projects" ?
yes
how do i disable that
maybe its just for this sessions like it says tho so maybe it iwll be gone when i close out and come back lemme try
it just makes saving my project when i make changes slower so its annoying to change something and then test it over and over
do you want the debugger? I'm not sure I understand what you're asking now tbh lol
im gonna be real, i dont really know what the debugger does lol cus unity seems to work just fine when i click the "cancel" option 😭 so i just click cancel each time
well thats what Attach to Unity does.. it makes it run with the debugger
debugger is used for Breakpoints so it pauses at that point in the code, so you inspect values
I happen to have a problem (while i have fixed the jumping which the player can jump normaly, but for the jumping frog power-up, when i hold down to charge up to perform a high jump, it doesn't perform a high jump for some reason. what do i do to fix this? or should i explain more?
private void FrogJump()
{
if (Input.GetButton(_jump) && _isGrounded)
{
_jumpBufferCounter = 0;
_coyoteTimeCounter = 0;
_currentJumpForce += (Time.deltaTime * _currentJumpForceMultiplier);
_currentJumpForce = Mathf.Clamp(_currentJumpForce, _jumpForce, _frogJumpForce);
_ani.SetBool("Jump", true);
_ani.SetFloat("JumpPower", (2 *_currentJumpForce)/ _frogJumpForce);
_rb2D.constraints = RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezeRotation;
}
if (Input.GetButtonUp(_jump) && _isGrounded && _rb2D.velocity.y < 0.01f)
{
_jumpBufferCounter = 0;
_coyoteTimeCounter = 0;
_ani.SetBool("Jump", false);
_rb2D.velocity = new Vector2(_rb2D.velocity.x, 0.0f);
_rb2D.AddForce(new Vector2(0.0f, _currentJumpForce), ForceMode2D.Impulse);
_currentJumpForce = 0.0f;
_ani.SetTrigger("FrogJump");
_as.Play();
_isGrounded = false;
_rb2D.constraints = RigidbodyConstraints2D.None | RigidbodyConstraints2D.FreezeRotation;
}
else if (Input.GetButtonUp(_jump) && !_isGrounded && _doubleJump)
{
_ani.SetBool("Jump", false);
_doubleJump = false;
_rb2D.velocity = new Vector2(_rb2D.velocity.x, 0.0f);
_rb2D.AddForce(new Vector2(0.0f, _jumpForce), ForceMode2D.Impulse);
_ani.SetTrigger("FrogJump");
_as.Play();
}
}
havent you been around here long enough to know how to share code properly 🤔
i know gdl, but seems to be unable to use it anymore. and i hae forgotten how to sent the code properly in text in here after for so long
!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/, https://scriptbin.xyz/
📃 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.
private void FrogJump()
{
if (Input.GetButton(_jump) && _isGrounded)
{
_jumpBufferCounter = 0;
_coyoteTimeCounter = 0;
_currentJumpForce += (Time.deltaTime * _currentJumpForceMultiplier);
_currentJumpForce = Mathf.Clamp(_currentJumpForce, _jumpForce, _frogJumpForce);
_ani.SetBool("Jump", true);
_ani.SetFloat("JumpPower", (2 *_currentJumpForce)/ _frogJumpForce);
_rb2D.constraints = RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezeRotation;
}
if (Input.GetButtonUp(_jump) && _isGrounded && _rb2D.velocity.y < 0.01f)
{
_jumpBufferCounter = 0;
_coyoteTimeCounter = 0;
_ani.SetBool("Jump", false);
_rb2D.velocity = new Vector2(_rb2D.velocity.x, 0.0f);
_rb2D.AddForce(new Vector2(0.0f, _currentJumpForce), ForceMode2D.Impulse);
_currentJumpForce = 0.0f;
_ani.SetTrigger("FrogJump");
_as.Play();
_isGrounded = false;
_rb2D.constraints = RigidbodyConstraints2D.None | RigidbodyConstraints2D.FreezeRotation;
}
else if (Input.GetButtonUp(_jump) && !_isGrounded && _doubleJump)
{
_ani.SetBool("Jump", false);
_doubleJump = false;
_rb2D.velocity = new Vector2(_rb2D.velocity.x, 0.0f);
_rb2D.AddForce(new Vector2(0.0f, _jumpForce), ForceMode2D.Impulse);
_ani.SetTrigger("FrogJump");
_as.Play();
}
}
A tool for sharing your source code with the world!
ok good.
I gotta run out for an hour but I'm sure someone will b able to look at it better
Log the velocity right after you set it
See if it's giving the value you expect it to be
well i tried this, it seems like it do increase, but not performing that for some reason
I don't see the velocity getting logged anywhere here
Okay, and is the value smaller if you don't hold it as long
yeah, like when i just click on the jump, i would just do the jump like the normal jump i did
Try also logging the velocity when you change it for other reasons. Right now it looks like you're calling your normal jump function at the start of update regardless of whether you are in the frog suit or not
like this?
doesn't seem to charge up when i hold down the jump button while when i let go it shows 13
hi so the game im making uses a raycast to check if you are on the wall, ground etc. For some reason only when I build my triggers count as a wall which they shouldnt because bumping into the wall affects your score. It works fine in the editor but webgl and windows builds both have this issue. All im doing with these triggers is SceneManager.LoadScene() on the OnTriggerEnter2D. My Collison for my player is on continuous and I am checking for the player tag on the OnTriggerEnter2D method. it still loads the scene it's just counting as a hit prior. Ive been working on it for a few hours couldnt find anything but pretty new so probably missing something
I shouldn't be doing that remove inside a foreach loop right?
No, that should produce an error . . .
You need a reverse for loop . . .
I did that last time and I already forgot....
It's such a stupid inconvenience.....
Like looping a list and removing stuff on it is one of the most common things to do, Remove should support that
Really, how so? It's just a loop, but in reverse. You're not doing anything extra . . .
The inconvinience that is basially doing a foreach but with extra steps and text
extra steps and text?
The problem is foreach. It uses an enumerator which takes a snapshot of the collection (list, in your case). You can't modify that collection while enumerating because the next item(s) will be out of place and cause errors when removed. That's normal and actually makes a lot of sense . . .
so... is there a way to fix that? because of that the number doesn't change while perfoming a high jump?
Why does the foreach moves backwards as if I was doing a reverse for loop to work for list like that?
It would make more sense to me
because by default they go forward and not backward?
Why would it make more sense for it to do it in reverse order by default
You mean, why doesn't it move backward, right? Because, to enumerate or iterate is to list or provide a way to move through elements, which by default, go forward, not backward . . .
also aside from just following the convention of counting numbers it's also generally not the responsibility of something inside an iterating list to modify itself like that
eg. in your example it's "odd" that a function just meant to get something out of a specific given list and actually messing with the list. Not intending to dunk on your code just pointing out because it's not ideally a common issue people have
I'd make an extension method that loops backward. Also, I forgot, Enumerators are read-only, meaning they're designed for reading data, not modifying . . .
Sure, the use of search for X occurrence on the list and if it happens just move it outside the list is such an odd thing to do right?
Like I dunno, feels one of the basic things a list should do
Debug.Log("Holding jump, current velocity: " + _rb2D.velocity); (like when I hold in to charge to perform a high jump, the number doesn't seem to charge up to the limit)
Debug.Log("Jumped, current velocity: " + _rb2D.velocity); (when I let go to do a high jump, the highest number for how high I jump shows, but doesn't do the high jump)
just explaining
(kinda yeah)
Well, let it read the data, but just read the very next item on the list but backwards, which is basically what I am doing, and while odd going backwards, it probably avoids more errors than it causes
Using a foreach is only for iteration; it cannot determine what your intent is when using that iteration You are expecting the foreach to not only iterate, but know that you are removing an item, so it must wait for each item after to shift down, then when MoveNext is called, it stays in place to check the same position again . . .
I understand your idea, but that's a different type of enumerator. There needs to be a way to determine if your enumeration is going forward (default) or backward . . .
gotta understand the scale of how many iterations people use in this programming language and how comparatively uncommon it is to remove stuff from a iterating foreach while also being very trivial to handle that by iterating backwards instead. They aren't going to add additional processing cost for what's a very niche and non-issue
@sour fulcrum if you wanna remove objects from the list, use an "reverse for" loop instead of foreach. Using a foreach loop would throw an exception when mutating it.
"reverse for" (is my ESL term lol) meaning you start from the end and iterate backwards as you mentioned. It's a very common practice when wanting to remove objects from a list.
-- and when you wanna add to it, using just a "standard for" loop.
@hushed hinge I think the problem is your code calls initateJump() at the start of each update. That method calls the method preformjump() which checks if you have released _jump button and sets _isgrounded to false. Then later in update, your code calls the movment() method which calls your frogjump() and _isgrounded is already set to false earlier
Also you should really consider smaller scripts. Jumping, moving, climbing, etc could all be different scripts cause they don't really need to know anything about each other
it makes issues like this 100x easier to debug
so, should i change something?
(im not the person having the problem and the person who is knows that)
@hushed hinge Honestly it's kinda hard to suggest exactly what to do because this script is doing so much. The issue I'm seeing is that handlejump() is handling your jump logic before your movement() method is called and so you've already performed a jump before your frog jump script is called
What I would do personally is moving jump logic into its own script. The only thing jumping needs to really know is if you're grounded. It doesn't need to be part of the script that handles all the other movement
Question for my game(I have no code rn about this topic yet, I've been organizing my plans and what order I should do things with the game dev. of my game)
I'm a beginner in coding kinda and doing stuff in Unity, I wanna know how can I make a reflectivity(aka rain that you see on usual radar apps) radar system where I can open a map and see rain/storms in areas, I have an idea on how to show the storms, but I don't have an idea on showing the map and storms in the exact correct position. So it would be helpful if someone explain how to code smth like this and how to do this stuff, because I can't find anything in tutorials that can be of use except tags
for me personally, i'd prefer not to or else it will changes everything around
@hushed hinge You'll have to change something around cause currently your code is trying to handle jump logic in multiple different places at different times during each update() cycle
i don't know what to change....
Your issue is that handlejump() and InitiateJump() are called first thing in your update method, which then calls preformjump(). Then FixedUpdate() calls your Movement() method, which inside of that calls either preformjump() or frogjump() again. But since you already handled jump logic in update, _isGrounded is always gonna be false
When you write scripts that get into several hundred lines of code like this that do so many different things, you will run into issues like this a lot and it is a massive headache to debug because you have to look through several hundred lines of code rather than a couple dozen. And you're having to look past logic for unrelated things except sometimes those things do end up intertwining accidentally cause you haven't seperated them
am i supposed to move these methods somewhere else?
You should have them in different scripts entirely really. Have a script that only handles jumping. The only thing jumping needs to know is if you are grounded, so it doesn't need to exist with all this other code
For example, my project I'm working on, the longest script is 112 lines. Now line count in and of itself doesn't mean your code is doing too much, but it's a good indicator
I had it like that before and it always worked. even the high jump always worked. but ever since adding in the buffer and coyote timer, some thngs doesn't seem right
Code always works until it doesn't. Your needs change and having code that's this hard to read through and maintain makes change near impossible as you are seeing now. What happens later when you add another suit that's a bird suit that lets you hold the jump button to fly up? Are you gonna add another couple hundred lines of code to this script? In the long run it will save you a ton of headaches if you make your individual scripts do less. There's nothing wrong with having multiple scripts attached to your player or whatever object
A rule of thumb I find is that I should be able to write what exactly the script does in the name of the script. This is for my golf game I'm working on so it's not the same as a platformer, but look at my Player controller. Each different input I'm doing is a different script. Each of those scripts is probably less than 50 lines each
well i still prefer not to separate that is already in the player2d script or it it will change everything everywhere
Ok well the issue is that your update and fixedupdate both try to handle jumping. You need to remove the jump logic from one of those
the one in update goes first and never calls your frogjump ability
Update runs every single game frame which can happen up to 100s of time a second if your framerate is high enough, while fixedupdate runs only when physics are updated, which happens at a fixed rate, I think the default for unity is 50 times a second
based on how I'm reading it, I would remove handlejump() and initiatejump() from the start of update()
and then change frogjump to use Time.FixedDeltaTime instead of Time.deltaTime at line 459
the F shouldn't be capital
oh
fixedDeltaTime, not FixedDeltaTime
ok, there
You should have auto-complete. just by using dot notation it should appear . . .
Since it says the definition doesn't exist, that's an indication you misspelled it . . .
alright, i removed both of them from the update
Try running that and let me know if you have any luck
nope, still the same
Idk what to tell you. This script is doing too much and is calling stuff multiple times in multiple places
your movement function is called in fixedupdate and update on lines 266 and 198. PreformJump is called inside of Movement at line 368 but it's also being called in initiatejump which is called in update as well
It's nearly impossible to read through this and understand what it's doing
!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/, https://scriptbin.xyz/
📃 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 did you mean by saying that changing the player2d script will change everything everywhere?
😢
private void CheckForInteractable()
{
Ray ray = playerCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, interactionDistance + 0.1f, interactableLayer))
{
IInteractable interactable = hit.collider.GetComponent<IInteractable>();
if (interactable != null && interactable != currentInteractable)
{
currentInteractable = interactable;
currentInteractableObject = hit.collider.gameObject;
UpdateInteractionUI(true);
}
return;
}
if (currentInteractable != null)
{
currentInteractable = null;
currentInteractableObject = null;
UpdateInteractionUI(false);
}
}
When UpdateInteractionUI is true it shows the text prompt. My problem is that while the ray is hitting the object it's flipping really fast.
@hushed hinge I'm not trying to be rude, I'm just trying to explain that the code is so jumbled that even you, the person who wrote it, can't read through it and understand what it's doing and when. You are gonna have to rewrite something to get this to work
Probably whatever you're showing also has a Collider and it blocking it
I've been trying my best over the past months, i managed to fix the normal jump issue, but haven't fixed the jumping frog one yet...
What I'm showing is on the UI and all interactable objects have to be in the interactable layer and this is the only object in the project that is on that layer.
how have you defined interactableLayer
Is this usually the correct method
I put my inputs basically all in the same script should I not do that
I assign what layers it is in the inspector. it's a public layer mask.
I really think breaking it into smaller scripts is your best option. The amount of time invested upfront in doing that will save you time in the long run. Your script has over a hundred lines just dedicated to declaring the variables at the top. Your jump code doesn't need to know about 95% of those variables
I've been doing it so anything that's handled that has to be saved and loaded goes in one script and anything that doesn't goes in the other lol
For the player controllers at least
@native thorn as with everything it really depends. In general having different scripts have single responsibilities makes things a lot easier to work with and test and debug
I find my UI ends up being a mess with 100 different scripts tho
I might look into doing that more for the gameplay elements
having every single different input as a separate component is definitely overkill. having it in one is fine
if you use the new input system too you can generate the c# code and see how they do it
It definately gets messy when I'm handling the weapons system and the controller and camera all in one file
or can i try to move all the jump methods over to the fixedupdate?
Use Debug Log to see what the Raycast is hitting if anything.
Seems like it's no longer hitting anything when you show the ui perhaps.
@hushed hinge that might be a good start yeah
Is there a somewhat easy method to serialising data for saving and loading
I do think you are doing well with your variable and method naming. Helps the code readability a lot
the existing json frameworks, like newtonsoft, already do everything for you
thanks, over the past months i've also been busy with some designs on how the world buildings might look like
@native thorn I've got a save system in my game that's pretty modular, lemme get the github link
Oh, so you set it up using a contemporary unity thing? I'm a beginner with this
I can make arena shooters and platformers my knowledge ends there lolb
@hushed hinge I like the art style a lot for your game too
not really sure what contemporary means in this context. you can just download it from the package manager. Json.net
@native thorn Here's the save system in my current project https://github.com/EdmondsNathan/GolfGame/tree/main/Assets/My Assets/Scripts/Saving
Sorry, I more so mean built-in
aw, thank you, each planet are also going to have different variants, like one world will be sci-fi, one will be water, one will be snow, one will be ghostly, one will be of sweets, and one which will be dark, while a bonus would will be stars and fantasy, the home world
Ray casts aren't normally bad with collision or something right?
I don't know why it's returning so many falses.
Thanks, is this still one of the standard ways you'd do it for unity 6?
Looks like it's hitting the door or the door trigger alternately
You should make sure only the colliders you want are included in the layermask
then yea its just accessible with the package manager and you should be fine to use it. Writing your own save system is pretty easy if you have a basic understanding of json
They're never bad with collision. They're job is to detect intersections with other colliders (collision) . . .
@native thorn It's implementing a standard unity package. Just go in the package manager, click the + button in the top left, "add package by name" and then paste com.unity.nuget.newtonsoft-json as the package
I'm about to leave work so I'll be afk for a bit, but if you wanna take a look through that code and DM me I can explain to you how it works in depth so you can adapt it to your game
The great and terrible thing about Unity is there's like no standard way of doing anything. It lets you do things however you want really
Ok I accidently did change layer of all children but after making sure only that object is in the only one in the layer the issue persists.
@hushed hinge assuming you're using Visual Studio, although this would work in really any ide, you should look into how to use a debugger. It will help a ton with figuring out the issues in your code
I'm very beginner I get as far as being able to break down unity specific info(game objects) into regular data
And can use that data to rebuild the game into the state I want
I'm just totally lost on storing and loading that data itself
It lets you set breakpoints that can pause your game when you reach a certain line of code and then step line by line through it and read what each variable is
@native thorn either tonight after I get home from work or tomorrow I can help you do that. That's what the code I sent should let you do with some tweaking
Alright thanks I'll have a proper look through it today, I've got no electricity for a week so sort of planning ahead right now lol
Wait. Can it be that it's because the raycast hit's it returns a true but then keeps going through it, hits nothing and returns a false?
oh yeah I remember you saying that, that shit sucks
just dm me if you don't understand any of it and I'll explain it
Good luck man.
Cheers homie
I do use Visual Studio. While i am not the best at coding a lot, i do came a long way, especially when i was at game design school, while i am more of a game designer
@native thorn Ignore the scripts in that folder that say "Async" in the title. Those aren't being used at all and are just gonna make it more confusing
Nah that's not how raycasts work.
@hushed hinge I would look up a youtube tutorial on how to use the debugger in visual studio with unity. I think you'll see quickly how helpful that'll be with fixing your script
We all gotta start somewhere. I'm no professional myself. I've just done lots of small game prototypes in Unity for years
Well i did tried that moving the jump methods to the fixed update, and remove movement from update, it seems to be working now
Ahh yeap, I'll deal with CPU performance stuff when I'm a lot further along lol
Hell yeah
Also just to double check I wouldn't have to be worrying about this during development right?
As in, will I have to backtrack and alter a lot, or is it simply just breaking down variables into simple data and then bringing that data back
For some reason saving/loading has given me endless anxiety about every decision I've made lol
Alright, thanks man
okay am i stupid or should PathList never be empty if Pathfinding.PathPos was EVER not empty (even if it currently is)
because somehow pathlist keeps getting reset to nothing when pathpos is nothing
oh is it
making pathList a refrence to PathPos rather then setting it
yep that was the problem
how can I find this missing script issue?
I looked at the scripts in blue and I don't see how it could specifically help me find this "(Unknown)" script
we don't really recommend dms here, fyi. most support servers don't. it negates the benefit of having community support
Click the warning message
It will navigate to the script
As to what script it is, idk. Try and figure out what it might be
it doesn't thats the problem
well it at least doesn't navigate to the missing object or whatever
because its deleted but your component still points to removed script
It should point to the missing script
If a script is missing, it specifies it is unknown on the component, and this warning triggers
But you should be able to click the warning and navigate to it, no?
If its in a prefab, it wont go there
As it is crying about your networkprefab from a packagecache, maybe try to readd the package or purge its cache folder
Hello everyone, I am new to unity and want to make a simple 2d crouch system in which the size and collider changes, but its bugged and not working. can anyone help me out? this is a part of the code
private void handleCrouch()
{
if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
{
if (!isCrouching)
{
isCrouching = true;
transform.localScale = new Vector3(transform.localScale.x, crouchHeight, transform.localScale.z);
collider2D.size = crouchColliderSize;
collider2D.offset = crouchColliderOffset;
Bob.gravityScale = 0f;
Bob.linearVelocity = new Vector2(Bob.linearVelocity.x, 0);
transform.position = new Vector2(transform.position.x, transform.position.y - (normalColliderSize.y-crouchColliderSize.y)/2f);
}
}
else if (isCrouching)
{
isCrouching = false;
transform.localScale = new Vector3(transform.localScale.x, normalHeight, transform.localScale.z);
collider2D.size = normalColliderSize;
collider2D.offset = normalColliderOffset;
Bob.gravityScale = originalGravity;
transform.position = new Vector2(transform.position.x, transform.position.y + (normalColliderSize.y - crouchColliderSize.y)/2f);
}
}
i wanted to take into consideration the displacement
can you please explain, what you mean with its not working and bugged?
well I attempted to make it crouch and when the character crouches, it would normaly stay mid air but I attempted to fix it, and it just goes down too much, I will try to record it with obs
First thing to consider, watch, what happens, when you manually in edit mode scale a transform with a collider on it
I do not understand
Your collider will get scaled too. so be sure you are not double scaling it or expecting a specific size when using transform.localScale in parallel
well I am trying to change it's size too but it is just not working as expected
this is a recording of it
And thats why I mentioned to check your scaling. If you scale the transform, it already wills cale your collider with it. so your crouchColliderSize should take that into consideration too
And I am not gonna download anything from here, sry.
If you output mp4, it should embed it correctly I think
here it is
So as I said, your crouch is already scaling your transform (including the component collider on it). And because you are offsetting and resizing your collider, it will ignore the physics for a frame and get stuck below your 2d ground collider I guess. How about taking away the whole collider resizing and test it with just the transform scale?
imma do it
taking out the colider and position transform it works but it still stays mid air
Than you can try the other way around. Do not scale your collider. Detach your visual gameobject from the collider object and just scale it visually with scale and set your collider as you did before.
i always write oncollisionenter like this but now apparently something is wrong because there is a yellow line under it, what happened?
what does it say when you hover it?
I would but it seems like it would be harder, I just started working with unity for a small game
also the moving of the position is not working
and here its fine for some reason?????
update: its because i named the script collision
that looks like your IDE is not configured correctly, as no types are highlighted for example
what do you mean?
!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
for colision is there any kind of rule to follow when should i use tags rather than layer colision and vice versa ?
you should use layers, generally
tags are for you to check in code. Layers can be used to exclude collision between layers, for example Player should not collide with itself or something
can layer colision fully replace tags
you can have enemies on the enemy layer but still use different tags on them if you need
@astral falcon how should I fix the height difference?
depends on what you're using the tags for
hard to say without any context
You'd usually want to just get component instead of tags
im still dont know when should i use it, just rellize i have 20 layers and 0 tags
but yeah generally layers are the way to go for primary control of what collides and what doesnt
Oh wait, I just realised you are using transform.position. Thats not gonna work with colllisions
You don't have to use them
that's fine
as tags are still a single thing these days and not an array, i do not know anyone, that is frequently using them. I guess the most know is "MainCamera" 😄
like tried to get into tags a few times but almost everytime switch out cause i rember it compare string
i guess its fine to continue with layers like this then fr fr
And about your issue with skipping collisions and stuff. Pleae checkout !learn about basic collision2d tutorials. Because you are mixing up transform.position with collisions, which is not going to work, as transform.position basically skips the entire physics check. And thats what you gonna see and learn in the tutorials. How to properly move your character 🙂
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
CompareTag doesn't compare strings. It compares hashes afaik.
components > tags when it comes to confirm if an object is what you are looking for
then layers are used to avoid checking that object in the first place
then now i just think tags are obsolete feels abit wrong
you can think of them as an unlimited number of layers that aren't integrated/used-by almost anything
oh yea layers limited, guess it can act as a backup
also tags compare strings if you use strings, otherwise they compare TagHandle structs
looking over some of them, they just pulled out a script and pasted it
whatever happens inside the engine with tags, 'nobody' knows
tags are gross, harcodey and pretty unadjustable at runtime. i've yet to see a reason why using a component isn't just superior
https://learn.unity.com/course/2d-beginner-adventure-game so you went through this entire tutorial, yes?
Immerse yourself in the world of game development with this comprehensive 2D Beginner Adventure Game project, designed to guide you through the fundamentals of creating an interactive experience. Follow along step by step to create your own 2D adventure game, with a choice of assets and options for customization along the way. Explore more 2D ...
MainCamera 🤣
i dont use that 😄
you can only have 32 tags though, no?
no thats layers
no they both have that limitation iirc
or is it an array?
i haven't touched tags in a long time, i might be misremembering
tags are unlimited
they end up getting baked down into likely fancy hash c++ shenanigans for runtime use though
can't add new ones at runtime
Hi guys, i have a problem with 2D colliders, my script doesn't work. I add debug logs but seems not enter OnTriggerEnter(). Can someone help me?
is the Trigger checkbox checked ? are they in same layer or colidable layer?
2d uses OnTriggerEnter2D()
fr
Yes, everything i want that collides has a box collider 2D o a circle collider with IsTrigger = true
Thank you sooo much
Now it show me this error
ok, 2 things ..
configure your IDE so that it gives you warnings in it.. and you can use google to go to the docs to find the exact signature required
!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
its right there in the console, what you need to do
when you've configured your IDE correctly, it will auto-complete the method for you
oh thanks, i wanted to have the auto-complete things that i see in the tutorials but i never knew how to do it
Something you should have goolged to find out how to then..
The #1 skill of a developer is knowing how to search the internet
I wanted to do it, but i thought it was more important to learn a bit first. However, i will configure now
No, it's more important to have your tools setup correctly
You only hinder yourself by not having it setup correctly - see this current problem as an example
I fix it, the problem was here: private void OnTriggerEnter2D(Collider2D other){}
OnTriggerEnter2D requires Collider2D type for other
yep, we know
that isn't a beginner question, better suited for #archived-code-general
I remember my Ruby game from back in the day. You ventured deep into the forest, ate the mushroom and the world’s color got flipped.
is there a way to get the button, text of a button, and stuff like that with an OnClick() event? I'm not quite sure how to word it, but I want to reuse a method but for a multitude of buttons ( so I don't have to make lots of different methods for each button). Is there an easy way of getting the button, and text of the button upon the OnClick() event firing?
Make the method the button calls retrieve the button reference
Yeah, that's the bit that I'm unsure of how to do#
Hello everyone, so I currently have a cube with text that can rotate like so. How can I make it so when the cube rotates, the text rotates so it's always is readable? E.G. the text on the sides is always upright and the text on the top also always faces the camera (Assuming the camera position is always locked)
that's not gonna be so straight-forward..
as u can't really make the numbers follow the camera at all times.. or else it'll look funny..
and if u only have it rotated at a 45* angle like it is.. theres usually (2) ways the number can face
atleast for the top number.. this is why Dies use dots instead of numbers 😄
thats the easiest solution..
i'll think on it.. i don't really have a solution in my mind atm
you could probably wait for the rotation move to be finished.. and then flip the numbers
hi, in this 9 second video youll notice the pillar im circling is super jittery cause of the camera. Im not sure how to fix this. should i show my code.
upload it as an mp4, discord can't embed mkv
i ask chatgpt and me and it tried to something about the the update method
i dont really understand it though
if you know a youtube video about it, ill go watch it
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed = 5f;
public Rigidbody rb;
void Start()
{
if (rb == null) rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float movex = Input.GetAxis("Horizontal");
float movez = Input.GetAxis("Vertical");
Vector3 move = transform.right * movex + transform.forward * movez;
rb.MovePosition(rb.position + move * speed * Time.deltaTime);
}
} (is this a 'large code block?')
ok i put it in paste.mod.gg/
negative.. but format it like this next time
public class Movement : MonoBehaviour
{
public float speed = 5f;
public Rigidbody rb;
void Start()
{
if (rb == null) rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float movex = Input.GetAxis("Horizontal");
float movez = Input.GetAxis("Vertical");
Vector3 move = transform.right * movex + transform.forward * movez;
rb.MovePosition(rb.position + move * speed * Time.deltaTime);
}
} ```
sorry
which serivce did u use
i didn't its discord formatting..
oh u just put 'cs' there
'''cs hi'''
nope.. those are apostrophe's
Don’t use ai if you don’t understand what it’s generating
the backticks are usually above the Tab key..
on top left side of keyboard for Qwerty
i get it to explain everything but i dont get the whole concept of the update system
theres like 3 updates
the camera is probably jittery just b/c the rigidbody runs on the physics tick
try using some interpolation on ur player (rigidbody)
that was gpt said
okay interpolation is an option of rigidbody thing right
a broken clock is right twice a day 😉
yessir
i dont know what this saying means but i heard it many times
do you have interpolation on your rb
chatgpt is random output. sometimes it's right. don't expect it to always be right
if a clock is stuck at 1:15.. its correct at 1:15 am .. and its correct at 1:15pm.. the rest of the time its wrong
oh yea true
it just means "even things w/ bad advice can accidently get things right"
lol.. ya chatgpt is a good tool.. just try to not rely on it for things u dont understand
it'll screw u over and not think twice about it 😄
if that doesn't work you can add some smoothing to ur camera via its code
doesn't even think once
i see what u did there
@wild parrot anyways, did the interpolation fix it?
if not, try setting the velocity instead of using MovePosition
or just use cinemachine 😈
does that mean i wont be able to use the rigidbody functions
no ill try this velocity
this is smoothing i was mentioning
nah, but you'll need to consider it..
if ur manually setting the velocity..
MovePosition and other Rigidbody stuff only belongs in FixedUpdate
It doesn't work properly in Update
no
why is that a bad thing lol
(is this a 'large code block?')
i was only responding to this question
u say i cant use it
no, you can use them
you asked if you couldn't use them
he said "no" it "doesn't mean you wont be able to use rigidbody functions"
so we're denying the negative part
lol
MovePosition also doesn't respect collisions for the moving object so if you need this thing to not go through obstacles you shouldn't use MovePosition as well
^ this is a big point u might want to consider
oh yeah this is probably the main issue
setting a velocity just sidesteps that
I think for the jittering problem this is actually the main problem
so even if its using the rigidbody, it wont do collision
I mean it will but only after it's been moved inside other objects
Resulting in a harsh deconfliction
okay it wont predict
Moving with velocity will properly stop it before it goes inside other things
okay i change my things to velocity
// every frame
void Update()
{
//get input
float movex = Input.GetAxis("Horizontal");
float movez = Input.GetAxis("Vertical");
movementInput = (transform.right * movex + transform.forward * movez).normalized * speed;
}
// physics frames
void FixedUpdate()
{
//use input
rb.velocity = new Vector3(movementInput.x, rb.velocity.y, movementInput.z);
}```
-# example code
let us know if moving the rigidbody function to fixed fixes ur problem
Hello all, When my inventory canvas is active, I click on a transparent area to close it, but my character also moves to the spot I clicked. I don't want this to happen.
In short, when my inventory is open, I don’t want anything in the background to be interactive. How can I achieve this?
disable the entire player movement script when inventory is open..
or if thers parts of it that need to be running.. you can use a boolean..
if(!canMove)
{ return; }
// the code that should run if you canMove```
That makes a lot of sense. Thank you so much, I'm trying it now.
another solution would be to make a transparent background image..
thats set to Raycast Target
that'd block any raycast from getting thru.. (if ur project is setup like that)
"Raycast Target didn't work for some reason. Since my character is a Rive widget under another canvas, I wonder if that's why Raycast Target didn't work. I couldn't figure it out."
not sure.. maybe something to do with the order of ur hiearchy?
Top gets drawn first.. then as u go down each element gets drawn on top of the next one
imo, its better to code it in place.. b/c u dont want clicks to do stuff not related to that menu.. but u'd also want keypresses and controller buttons to not affect anything else either..
soo maybe the bool would be the best choice.. or disabling scripts
Thank You!
it'd be a great time to work on a game manager
a singleton that would monitor that.. and have control over other things that need toggled
you're right.. i tested it myself.. it will block other UI stuff but raycasts from the camera seem unaffected..
probably b/c of the way UI is drawn.. not too sure.. (so thats why i stressed the other method).. it'd be a better robust alternative
i knew that was a bit too cheeky to actually work 
raycasts don't affect UI (I believe), UI uses graphics casting
ya, my first attempt i forgot to add my graphic raycaster to it..
so after doing that and it still not blocking any of my IInteractable stuff made me sure
that reminds me.. I always put off stuff like (disabling this and that when my menus are open)..
my projects get a bit crazy when i have UI open over top of the game itself.. 😄
i need to take my own advice and make me a little game-manager right quick
I think I'll block the interaction somehow after the inventory is opened, but the UI is causing problems where it overlaps with the walking area. When I click to open the inventory, the character also walks towards that direction because I’m clicking on the collider.
you need to add a check to your "point and click" logic to check if (!IsMouseOnTopOfUIElement()) first
it's not a one-liner by default, so you'll need to set up a method for it, but it's a one-time setup then you make it a one-liner
didnt dictionary had support for accessing null keys?
if dict[5] == null screams that 5 dont exist but im pretty sure i could do that
you sure it was c#?
using dict[5] assumes your dictionary is Dictionary<int, object>
yes but it errors if 5 int dont exist
and you're trying to access the object whose key is registered as 5
entries with null values and nonexistant entries aren't the same, btw.
-- this is NOT the 5th element
yes i know
ok yes then you can definitely do dict.Add(5, null);
of course you can add null but you cant access them if they are null
but i think you could do that
it's just a dictionary -- a map
you can add ANY values if the key is correct, and you can retrieve it back
@late burrow
that's not true btw
an entry just needs a key and a value to "exist" in the dictionary
the value being null doesn't invalidate its existence.
like i dont know whats the problem shouldnt it just give null?
KeyNotFoundException: The given key '5' was not present in the dictionary.
there's something else wrong in your code, likely. If you wanna share more I can try to point it out
you just never added a value in the dictionary with key = 5
yes but im 100% sure i didnt had to add them like that if they are primitie
yes, this is what im talking about
the value being null and the entire entry not existing are not the same thing
OH sorry you said AREN'T 😄 Yes that's 100% correct then mb
you can check if key exists and is not null by doing:
if (dict.TryGetValue(5, out var val) && val != null)
To be clear, you're conciously aware that you did not add a key 5 to your dictionary and you're asking why it's throwing an exception when you try to access a non-existant key?
or you can check if key doesn't exist OR is null by doing:
if (!dict.TryGetValue(5, out var val) || val == null) { return; }
yes i know i didnt added because im doing the loop that puts whatever it finds into dictionary
and didnt wanted erase existing contents
guess ill haev to do this then
yup! super common practice
no
maybe, but i swear it wasnt throwing error before
You're probably confusing with C++ maps. They can add new elements via the indexer.
just giving null
it'd give null if 5 was present but null
or js objects/maps
it likely wasn't throwing an error before because you had an entry added with key = 5
or i just got brainwashed by json
maybe 😄 json indeed only parses what matches no problem
what...
if(testDict.TryGetValue(5,out var value5))
{
if(value5 == null)
Debug.Log("Key 5 exists, but its value is null.");
else
Debug.Log($"TryGetValue: Key 5 exists with value: {value5}");
}```
ahh dang.. someone beat me to it
we C# people can add new entries via the indexer as well! Like: if (!dict.ContainsKey(5)) { dict[5] = null; }
nvm that was the way i did it
just instead of == null containskey
and you can indeed then write dict[whatever] = null
that doing lookup twice, CollectionMarshal.GetValueRefOrAddDefault would be nice for this
we're in #💻┃code-beginner 😆
ah shiet,, yeah forgot that
we're strictly Lists and Arrays over here bruh
😆 j/k j/k Dictionaries are welcome too
yea yea totally welcome...! in #archived-code-general 
I'm now trying to prgramatically add an image to each face object, which I am trying to do as following
for(int i = 0; i < transform.childCount; i++)
{
GameObject Go = transform.GetChild(i).gameObject;
if(Go.name[^4..] =="Face"){
Button b = Go.transform.GetChild(0).GetComponentInChildren<Button>();
var sprite = Resources.Load<Sprite>("pip"+Random.Range(1,10));
b.image.sprite = sprite;
}
}
But the scene loads errorless and imageless. The images I am trying to place on the buttons are under Assets/Resources/pipX.png, with X being a number 1-9
I've also confirmed that it enters the if correctly
How would i go about more efficiently running a function every other frame? An if statement in update? Corontuines?
more efficiently than what?
and would it really make a difference lol
the work you do is probably more intensive than triggering it
sounds lke premature optimization
it might in terms of devirtualization. devirtualized virtual methods will be faster
if (++i % 2 == 0) { MyMethod(); } would be fine I think.
Alr, ty
but would it be significantly more? probably not
that's a microoptimization at that point
would i just use a variable that infinitely increases for this or would it be better to recent whenever it runs
no, when devirtualized it will use call instead of callvirt
meaning, the same overhead like normal methods
doesn't really matter
can you debug the values ur using to make sure they are what u expect?
use a separate variable called frameCount. If you REALLY wanna make it robust make it ulong or add another line that resets it when it reaches maxvalue 😆
if theres no errors i'd guess that the code/logic is correct.. but maybe the images aren't what u expect
for an int32 it would overflow after 3 months at 240fps
you're safe with an int32
an unsigned long type (ulong) can represent a number up to 18446744073709551615, so this logic will ONLY run for 18446744073709551615 frames
that's similar to what tetris devs thought about max score 999,999
ah yes, ONLY 2437260 millenia
That should be fine long, dont think any game will be ever left running that long
Which values are you reffering to?
the gameobject, the button, the sprite
The images look like so
all of em lol yea, make sure ur getting those names correctly..
im not really sure how u'd debug to see if its selecting the correct image
It's easier to do a simple comparison instead of the modulo operator . . .
like this?
if (frameCount == 0 || frameCount == 2 || frameCount == 4 || frameCount == 6 || frameCount == 8 || frameCount == 10 || frameCount == 12 || frameCount == 14 || frameCount == 16 || frameCount == 18 || frameCount == 20 || frameCount == 22 || frameCount == 24 || frameCount == 26 || frameCount == 28 || frameCount == 30 || frameCount == 32 || frameCount == 34 || frameCount == 36 || frameCount == 38 || frameCount == 40 || frameCount == 42 || frameCount == 44 || frameCount == 46 || frameCount == 48 || frameCount == 50 || frameCount == 52 || frameCount == 54 || frameCount == 56 || ...
{
MyMethod();
}
as far as I am concerned it looks like pain
True honesty this is most effective
in what way? 😄
simple and readable code is often the best
bool check=false;
int max_ = 1000;
for(int j = 0; j <= max_ && !check; j += 2)
if(frameCount == j)
check = true;
haha, you funny . . .
if (++_frameCounter < _intervalFrames) return;
MyMethod();
_frameCounter = 0;
I believe this would do the job
i think I found it. in a 3d environment pngs are imported as textures not sprites
or this
so i just need to convert to sprite probably,,, but maybe it's a good idea to see if it can be done with textures
how do i make it so that visual studio gives me suggestion to complete my sentence?
this code needs an exorcist
!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
idk I still feel this code is the simplest if (++i % 2 == 0) { MyMethod(); }
same response.
oh T_T
The modulo operator is more expensive because of the division instead of a simple comparison . . .
not true, the compiler should be smart enough to avoid expensive stuff... well unless unity can't avoid bad codegen so uh...
either way, here's a way to avoid modulo with bitshift for even/odd operations based on that posted use case
bool IsEven(int val) => (val & 1) == 0;
I need to watcg a video on bitshift i dont understand it at all 😭
you rarely need it, so you're not missing out much 😂
bitwise enums: "Am I a joke to you?"
you will need it once Unity is done migrating to coreClr..
bitshift is heavily used on vector generics (Vector<T>/Vector128/256) for SIMD stuff
Haha, I have this exact same extension method . . .
/// <summary>
/// Determines if an integer is an even number.
/// </summary>
/// <param name="val">The integer value to check.</param>
/// <returns>True if the integer is even; otherwise, false.</returns>
public static bool IsEven(this int val) => (val & 1) == 0;
nice
No, it never did. A dictionary validates its key with this method: https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.cs#L1685
You should not assume it works anyway, because null would be a very vague key since it's not a value
you can with CollectionMarshal but that's unsafe
he uses layermask as the example.. but its a good video on bitshifting and stuff imo
also not sure how it would behave in unity tbh
after learning about bit shifting endianness is a fun next topic! /s
Yes but this is the code beginner channel and I really doubt they have used it
ah yeah, the second time I forgot this today... my bad
we need someone to come in with their mouse delta's multiplied with deltatime to help remind us
I followed it (first one) but nothing seems to be new.
does this look alright?
no
rekt
idk I am trying but it is not working
make sure your have no compile errors in unity. If you followed the set up correctly then close visual studio then open it again in unity via the ASSETS > OPEN C# PROJECT menu.
that will make it open the visual studio solution (the fancy project file)
why doesn't this work
'''
cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
[SerializeField]
public float mouse_Sensitivity;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = transform.position +Input.mousePositionDelta *mouse_sensetivity * Time.deltaTime
}
}
'''
backticks
what are those
`` `
woah how did you do that!!1!1
magic 🌈
oh god this is physically painful how do people troll
#include <UnityEngine>
class MyScript : MonoBehaviour
{
public:
void Start() {
int* myInt;
Debug::Log(std::format("test {0}", *myInt));
}
private:
void Update() {
}
}
guys my script doesnt work help /s
UnrealUnity
well, you're trying to use an uninitialized variable.
ding ding you win
hey at least its not python
it would sigsegv due to the nullptr deref
I recommend studying a bit more about Unity code and C# in general before jumping straight in game dev 
yes i will go read up on python for unity
wouldn't it be a random value, rather than guaranteed null?
that's the spirit!
tbh im not sure, I want to say that most compilers would not do this to prevent stack leakage
import "UnityEngine";
class MyScript extends MonoBehaviour {
public Start(): void {
Debug.Log(`Start from ${this.constructor.name}`);
}
}
what's this damn language
ts
why this.constructor.name is allowed lmao
because that's how js works
oh lol wow
the opposite
i mean that the lambda will capture this from the scope it was created in, vs the calling this later.
tested and got random value, assuming that local variables work the same regardless of if they're free or a method
oh it's not captured
oof, this is why we need more rust
the behaviour is that function() {} creates a new this context, while () => {} does not
() => console.log(this) will give different results depending on where it's called from
I wasn't aware of this and was fighting a bug at some point for an hour or so lol after refactoring some code
ended up solving it by caching a local variable but still not realizing why that'd fix it
import unityengine as ue
class MyScript(ue.MonoBehaviour):
def Start():
Debug.Log("Hello world")
all py examples i see always shorten the longest import you have ever seen into a
import supercoolclibwrapper as s
import unityengine as MyCustomEngine_I_MadeThis_btw
fuck it
section .data
message db "Hello world", 0xA
message_len equ $ - message
section .text
global _start
_start:
mov eax, 4
mov ebx, 1
mov ecx, message
mov edx, message_len
int 0x80
mov eax, 1
xor ebx, ebx
int 0x80
import pandas as 🐼
this isn't even unity anymore 😭
Unity Assembly ™️
we kinda exhausted our options, huh
ran the train right into a brick wall
I did everything and it still doesn't autocomplete it in this 
bruh i edited the "number or text" to "message" and it didn't save
have you regenerated the solution, then validated that you have the solution open?
screenshot your Solution Explorer
good question, what is that
button in Preferences
I hope you mean this
(Unloaded)
right click it, Reload with Dependencies
where
where it says Unloaded
please believe me i don't see where it says that
well you need glasses then
maybe
look carefully to the window I told you to look at #💻┃code-beginner message
do you see the tab labelled solution explorer
I asked gpt and he told me where to look and finally found it
consider not doing that
civilization is doomed
it disliked your usage of gpt
as it should
(microsoft wants you to use copilot instead)
I dont understand how its easier to ask a chatbot than look with your eyes
will you need chatgpt to tell you how to piss
I stared at it for 3 minutes and didn't saw it
I WON, FINALLY
this visual studio is not configured correctly
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
did your discord not update ?
Do someone have good youtube toturials for C# or something other than youtube?
check pin
thanks
personally I preferred when I started
https://learn.unity.com/project/beginner-gameplay-scripting
&
https://dotnet.microsoft.com/en-us/learntocode
thank you so much
now my computer is exploding after i render my animation in blender
hey im working on a 20 sided dice but the debug log is showing the wrong number. is there a way to fix that?
ya make it give the correct number
debug log is showing the correct number for the time it spits it out
is there a way to assign a number per roll?
yeah why not
https://catlikecoding.com/unity/tutorials/ is a good'n
I have two classes, Player (which doesn't have the title in the screenshot, sry, but its just the smaller picture one) and TestingEvents. I'm learning about events and I think the way they're supposed to work is if I invoke an event in class A, a different class B can "hear" that the event was invoked and then perform a desired function that was defined in class B. <--- assuming that's correct, I'm trying to do some stuff using that logic (I might be wrong about those assumptions and maybe that's my issue though.)
So I have some code that tests whether space was pressed, one time with a function defined inside TestingEvents class, and another time with a function defined in the Player class. The Testing_OnSpacePressed() function works (defined inside TestingEvents) and spits out "Space!" in the console, but the EventTester_OnSpacePressed() does not seem to work (defined in Player). I assumed since OnSpacePressed?.Invoke(this, EventArgs.Empty); is getting invoked inside the Update() method in TestingEvents that the EventTester_OnSpacePressed() would be triggered since I attached it with eventTester.OnSpacePressed += EventTester_OnSpacePressed; in the Player class. Any thoughts on this? do I have a fundamentally flawed assumption about how events work? I was hoping to join a voicechat to get some verbal help with this but i dont think unity discord has voicechat, if somebody has a mutual server we can join a voicechat there
TestingEvents Class: https://paste.ofcode.org/rASCtxvdZwQXV5giv2hht
Player Class code: https://paste.ofcode.org/iHfmnEBdMnQtBw6HdLevJb
You cannot use new on TestingEvents to create an instance, because it is a MonoBehaviour. It is not allowed to do that because Mono scripts must be attached to a Game Object. When you use new that won't be the case. That is most likely why it's not raising the event at all
Also you're subscribing with += in Update, which is executed every frame. Given a framerate of 60 FPS, if you raise the event after 1 second, your OnSpacePressed() method will be executed 60 times!
im sort of following what youre saying, would you mind hopping in a voicechat if you have the time?
no worries if not
yo i am using a RayCastHit2D to check if im hitting a wall and for some reason only on build it hits triggers even though I contact filtered them out and turned off queries hit triggers in settings im so confused ive been messing with it for hours and I cant figure this out. IT's so weird that it only happens on build( and it happens for both webgl and windows) I even tested it on my laptop and it still happens. It's important because im resetting the score on wall hit, and it works fine on my item but it breaks on the collider that has SceneManager.LoadScene(). Any ideas??
how would i go about getting the angle between the red square and the blue square as if it was on a circle? like in this case it would be around 145. i tried vector3.angle but it doesent seem to work the way i want it
You mean the angle between the two black lines?
yes
The direction pointing out of the screen
in this diagram
or use the 2D version
if you have 2d vectors
hm it still appears to be in the wrong position but i think it might be from something else
Vector3.Angle would also work perfectly here btw (and will work as long as the angle you are looking for is less than 180 degrees)
so my guess is you are passing in the wrong parameters
Maybe show your code?
its gonna be more than 180 atleast the way im trying to
alr 1 sec
you are doing SignedAngle using position vectors
that's wrong from the get go
oh
it works with directions
to get directions i just normalize them right?
In your image here you need the direction from Blue TO Red, and the direction from blue TO the end of that black line on the right side of the circle
those are the directions
no...
To get a direction vector from point A to point B it's B - A.
(you can normalize that result)
yeah thats what i meant woops
you need a point C here
which would be the rightmost part of the circle in your diagram
C would just be vector2.right * radius right?
- the center
of the circle
Unless the blue position happens to be Vector2.zero
otherwise it'd be blue + Vector2.right * radius
though the radius isn't going to matter for these angle calculations
the direction itself might just be Vector2.right if you always want it to be that
oh actually that makes sense lol
yeah for the second one if you always want it going straight right you can just put Vector2/3.right
i got a - 67 from what should have been 150~, weird
ur normalizing the position itself before ur computing the delta
ur supposed to normalize the difference between the positions
Also which one is the red and which is the blue between player.transform and this.transform
player in the middle
then you want this.transform.position - player.transform.position
if you want the direction from the player to this object
dir from A to B is B - A
alright, btw is there a reason for using this.tranform instead of just transform?
oh okay
Could someone explain to me why setting variables in inspector vs programmatically is considered bad practice? The obvious is that you can lose those references (when errors happen, moving scripts etc) but are there other reasons?
would this (player and ghost) not be like 150*? im getting -170 which would be in the third sector( below left of player)
what's the player
the blue shirt guy?
yeah
Ok so:
The angle returned is the signed counterclockwise angle between the two vectors.
according to: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector2.SignedAngle.html