#๐ปโcode-beginner
1 messages ยท Page 141 of 1
no
cuz if not ur question should be "Why doesn't my if() conditional even run
did you set up the "e" button in ur input settings?
b/c if not it wont work..
KeyCode.E would be an alternative
that would work regardless b/c its a generic Input
ill try it thx
if (Input.GetKey(KeyCode.E))
{
Debug.Log("e pressed");
sword.SetActive(true);
}```
when you just use something like "e" it would need to be set up in the Input's so Unity knows what "e" even is
KeyCodes are easy to use when prototyping
it worked thx
how do i make a dash that has the player like flicker in and out
probably a shader or visual effect of some sort
u could just enable and disable the Renderer component..
im also struggaling with the actual dash part to
could make that in the animator
to fake it
hello! i just started learning unity and ran into this problem, where only the idle animation is visible and others are not (only the outline in preview is visible). how can i turn them on?
do a animation clip that changes the alpha of your character and move it some units forward
make sure the graphic is IN FRONT of the background
ur Z position is 0.. probably the same as ur background
u should move it a little forward towards the camera..
so it stays on top
well my 2 problems is 1 how do i figure out what direction to move them in and i have tried this to move them and it doesnt work
rb.AddForce(new Vector2(dashDirection.x * dashSpeed, 0f), ForceMode2D.Impulse);
dashDirection is just equal to transform.right
just to test it
well, you can do it by transform position if you use the animator
but you may want to also do an additional raycast check so you dont teleport into walls
u can animate the graphics only.. then still use ur physics to move it
well my physics isnt working
weird thing is if i switch it around to apply the force to the y axis the player moves up properly just doesnt work on the x axis
well.. if u move it upwards u lose contact with the ground..
if u moving laterally u would remain in contact with the ground..
could the ground and the drag/friction/ stuff have anything to do with that?
try changing values... give it a BIG force and see what happens
i did i gave it like 1000
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
what is the default layermask that doesnt filter anything?```cs
public static Collider2D[] OverlapCircleAll(Vector2 point, float radius, int layerMask);
https://gdl.space/ecasemivap.cs i am trying to print the int the is Amount in this code but it logs "Script or property 'Amount' not found" and i know that it is not finding the Amount int, can someone help
Default is the "Default" Layer
ohh so -5
check if player is grounded without using raycasts and ground layers (2d)
when smoothly changing things in unity, is something like DOTween the standard, or is there something I'm missing?
very interesting code, but you should be specifically targeting the type of your script and not mono
ya that code is confusing..
but i am trying to make it so that it can get any script and i dont have to change anything
trying to make an item pickup
why would you need to get any component?
use an interface if you want a specific group of separate components
Amount is a int in another scripts
target by interface or abstraction class
what is interface
good time to learn them
in Unity you can Lerp, and Slerp, etc
DoTween is basically a library that does the same type of thing but with many more features..
so do you use DOTween (or something similar)? or are you writing your own coroutine every time you wanna animate something
would it be okay to just continually set the text value in update referencing my stats. That way I don't have to update this manually each time a stat changes?
yup, u can use interfaces. they're basically contracts.. meaning if you make an interface that has a Amount variable then all the scripts that use that interface MUST have an Amount variable. same for functions..
this way when you try to get something thru an interface you know that it MUST have the things ur searching for..
thus making it much easier to access stuff like that
i use DoTween
i would personally recommend using an event and just invoking the event when a stat changes. then the objects can react and update the text themselves
^ yea, the common consensus is the opposite of what u just said.
u want to try to update things like UI as little as possible..
oh like check if the stats changed on a frame then update if true?
if it doesn't change you shouldnt need / want to update it
like if you attack something and it damages your stats. u can Tell the UI to update itself.. b/c u know u just got damaged..
updating perframe is the lazy version, best to just cahnge it when some value change
no, use an event. that is a specific thing. you won't need to do anything in update if you just use an event
isntead of checking every frame.. to see if it changed
void DamagePlayer(int damageTaken)
{
// the player just got damaged..
PlayerHealth.value -= damageTaken;
// then the UI should Update
MyUIManager.UpdateHealth(PlayerHealth.value);
}```
just an example snip
.UpdateAllStat()
also PrimeTween is the sexy new tweening library on the block. allocation free, allegedly better performance, and still fairly easy to use
would a private serialized variable be named _myVariable or myVariable?
up to you..
myVariable is what i use..
becaues my local variables use the underscore
either one. c# conventions state _ prefix for non-public members. whether it is serialized or not has nothing to do with the naming convention
alr, just getting caught up in microsoft docs lol
Me who is sticking to freestyle convention: 
lol..
freestyle whooooh
underline is one too many extra keys to press
yea i only mostly use underscore as variableseparator
public static IEnumerable<T> Circle_GetAllComponent<T>(Vector3 position, float Radius, int layermask = -5)
=> Physics2D.OverlapCircleAll(position, Radius, layermask)
.Select(x => x.GetComponent<T>());```
makes more sense in python since it's more concept than actually enforced
and javascript, but javascript is bad
how can i add a child of a prefab into a transform variable in a game object?
how do i get the direction to dash my player in
ping me if u can pls
same way you move in a direction
how to refrence a variable from another script and do the scripts have to be attached to a same object
so like this?
What's the value thing for?
Is NailController.EnemyLife a Type?
If not, then this should be a compile error and underlined in red
nope its supposed to be an integer
you may want to visit the beginner c# courses pinned in this channel to learn wtf you are doing
Then step 0 is to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
So stuff like this shows up as errors
how can i tell when the dash stops?? so i can enable the sprite renderer again
How long is a dash
i got it
transform.getchild(index).gameObject
idk i just do rb.AddForceX(100 * dashForce);
is coding usually for writing plugings?
Then I'd say the first step towards finding out when a dash is over is to decide what that even means
I have no idea what you mean by this question
This is less of a dash and more of just moving really fast temporarily. Your only option here would be impose your own time limit, or check the velocity (which will be inconsistent times)
what should i do to make it more of a dash
Hard to say, given I have no clue how your game is supposed to function. What's the use case, what do you need to know the end for?
im trying to make a cool dash effect and thought a cool effect would be have the person basically flicker in and out
That's really up to you. "Dash" isn't really a concrete thing you can just slap into whatever you're going to have to decide how it functions in your specific project
kinda like the effect given when goku uses instant transmission
like do you need to code to actually make something decent? or is it just to advance and cultivate the experience? like plugings
You will not be making anything with zero programming
This has no relation to what I asked, making it cool doesnt help me know what you need the end of the dash for. You probably want to just use a timer
i need to reenable the sprite renderer at the end of the dash
im used to making games in rpg maker with limited javascript knowledge to write some plugings i have no idea also-
not-nothing is not someting im aiming for, off to learn code thanks
how do i fix this so it moves the same distance but slower
Apply less force for longer.
wont the decrese the distance though
If you apply it for long enough, no.
so what just like have a coroutine apply the force multiple times?
Are you applying it once currently?
yeah
Preferably fixed update if you want it to be precise. But a coroutine might work as well.
any experts in character movement know a good tutorial?
Experts presumably wouldn't be using tutorials. You should be asking the beginners. ๐
any beginners have a tutorial for good 3rd person movement?
As an "expert" I can say: google!๐ฌ
!bugs
๐ชฒ To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
๐ If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click โReport a problem on this pageโ!
๐กIf your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
how can i fix this?>
this is still causing the issue
startRotationY is a struct too
do i have to make a var for that too then
It needs to be copied, modified, then copied back
how do i copy it bback? theres no setter
am i doing this wrong ๐ญ
assign to main.startRotationY not throwPuffs.main.startRotationY
like this?
yes
Okay tha k you !
playing with procedural mesh generation, and I was able to make a grid with some perlin noise for hills. The vertices that are in water are not displaced at all
I'm thinking about "hiding" the faces that are in the water, and I could do this by skipping creating a triangle when I loop over the grid
if I do that however, would that be a bad practice since I'll have a lot of extra vertices that are not assigned to any triangles?
It would be best to not include the vertices that aren't included in any triangles, yes
okay, that makes things really tricky then, since with a grid the vertex indices are ordered and predictable, which makes assigning triangles as simple as having two for loops, one for columns and rows
but if I remove vertices, the indices get messed up :(
Shouldn't be too hard if you do it in a second pass
there's a way to do that? I thought I had to assign the length of the vertex array from the beginning
Run your current code. Put every vertex that's in a triangle in a HashSet. Afterwards you make a new array from those vertices
You'll have to just map the old indices to the new ones for the triangles
interesting. I don't know what a HashSet is so I'll have to look that up, but thanks for the tip ๐
hey guys its been a while. I want to get back to game development. I want to take the snake game that I made and make it ONLINE multiplayer (currently I have local multiplayer). What is the best library/package to do this?
I've heard of NetCode. Is this the best one? or do you guys suggest anything else?
Thanks in advance.
There's no "best" one. There are many frameworks all with their own capabilities, benefits, and drawbacks
Do you have a short list (maybe top 3) so I can look into them?
Unity's netcode, photon and mirror
Photon is a company that makes several frameworks btw
check the origin of your model
if it's skewed off to the side, you'll need to fix that in blender or something
assuming that's what you mean
post a video of what's happening
when you click on your model, the box thing should be in the center of the model
for you, it looks like it's near the right arm. you'll have to fix that
your object is not centered on the parent that is being rotated
or that
also if you're running this code in update, you don't need Time.fixedDeltaTime
change it to time.deltaTime
Is there a built in way to compare components and/or gameobjects from a prefab with the same one from a instance of that prefab?
eg.
PrefabAsset
-GameObject Apple
-MeshCollider
PrefabAssetInstance
-GameObject Apple
-MeshCollider
i wanna compare the meshcolliders and get a correct result
hello can anyone help me solve this error:
NullReferenceException: Object reference not set to an instance of an object
MouseDrag.OnMouseDrag () (at Assets/Scripts/MouseDrag.cs:24
how to debug a NullReferenceException for future use: https://unity.huh.how/runtime-exceptions/nullreferenceexception
your issue is that your camera is not tagged as MainCamera
Do you have a camera in your game objects list? 
Oh, does it have to be tagged as MainCamera? Otherwise Camera.main doesn't work?
yes
Aight, didn't know that, thanks!
https://docs.unity3d.com/ScriptReference/Camera-main.html
The first enabled Camera component that is tagged "MainCamera" (Read Only).
If there is no enabled Camera component with the "MainCamera" tag, this property is null.
Thanks mate for the help it worked
Got it, thanks!
my task is to generate server log files for last three game session if any error occured
1 game session : start the game (run) to closing the game
the file generate will be like
- error1.txt
- error2.txt
- error3.txt sorta like this
i know how to obtain data and write files already, my worries are how to know this is the x times u opened the game
because how many time u opened the game, or nth game session is not recorded at all
Then you'll need to record it. By game session you mean players joining the server or server starting and shutting down?
the definition of a game session in my case is when the run initiated , started , all the way to app termination
client app
Ok, it would need to send some log in/out request and the server can keep track of each user session count.
i did come up with a solution, when the client started, i will do
int counter = PlayerPrefs.GetInt("nthsession");
PlayerPrefs.SetInt("nthsession",counter++);```
maybe in game manager
public int nthsessionbase3 = counter/3 +1;```
Storing it on the client side wouldn't be very reliable.
it is for debug only, for the whole dev team, so i was told to generate file locally
and using local data
Okay
Can we like grab the current active scene's yaml file to save the whole scene?
have anyone ever done a whole scene save system before?
private void HandleOrderRX(OrderRX orderRx)
{
float pitch = 1.0f;
// Check if the orderRX is in our list
if(order_rxs.Contains(orderRx))
{
orderRx.SetListeningForOrders(false);
order_rxs.Remove(orderRx);
pitch = .9f;
}
else
{
order_rxs.Add(orderRx);
orderRx.SetListeningForOrders(true);
pitch = 1.0f;
}
clickSounds.pitch = pitch;
clickSounds.PlayOneShot(clickUnit);
}```
not sure why this would error.
lol, hmmm nvm seems to have fixed itself.. i closed down my code editor and was gonna get 1 more screenshot of the error and I can't reproduce it again
Very noob question (smh my head):
I want to create a custom class MyButton that contains a string, KeyCode, Sprite, etc.
Next, in Unity, I want to assign all of these values in a [SerializeField] so that I can create an array of MyButton[].
Essentially, Iโm getting
When what I want instead are empty boxes for me to fill in each instance variable for each button.
How do I do this? Or should I even do this at all (is this bad practice)?
public string buttonName;
public KeyCode keyCode;
public Sprite buttonSprite;
public Sprite buttonHeldSprite;```
nope. its back.. it seems that If I have this script's inspector open it crashes when selecting and deslecting the unit..
but if i don't it wont.. ๐ค
does your class need to inherit from MonoBehaviour? if not, then remove that inheritance, mark the class as serializable then you don't need to do anything else to make it work
oh yeah that makes sense thanks
Directory.CreateDirectory($"{Application.persistentDataPath}/ErrorLogs");```
this will not give me an error if the folder is created right?
yup, thats it! when the inspector is open it causes the error.. along with a few other ones
its just do nothing?
Creates all directories and subdirectories in the specified path unless they already exist.
nice
fix works, thank you!
ive always wondered
if i make a class that inherits an interface
then i make another class that inherits from the first class
would the interface also be inherited?
private void GenerateServerErrorLog(DateTime time, string code)
{
Directory.CreateDirectory($"{Application.persistentDataPath}/ErrorLogs");
string path = $"{Application.persistentDataPath}/ErrorLogs/ServerLogs_{GameManager.Instance.nthErrorSession}.txt";
//clear previous n-3th error logs
if (firstWrite)
{
File.WriteAllText(path,"");
firstWrite = false;
}
//append all errors found in this game session
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine($"client server error found ! (code: {code}) >>> time : {time}");
}
}```
yes
finally got it done
hot
also this is a bit pedantic, but you don't inherit from an interface, you implement it
aighty
it doesnt add up the text tho
In C# is there a performance impact calling a method nested in another method? I used to use another language that had a pretty large performance impact to run a nested method so I've always been hesitant to nest methods in C#.
Not enough to make difference in most cases.
Obviously, it's jumping pointers, so there is some overhead. But it's also possibly inlined by the compiler.
compiler turns local methods into internal/private static methods right in the class
https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQMwAJboMLoN7LpGYZQAs6AsgBQCU+hxTAcnQNyNNHnqu2dcCSLsQC+A8cOIC0mCnwFCRRAG4BDAE7oAHugC86AAwcpIvieXcKNfqZFLLTbWDAXLkppNFA=
Whats going on in here
I wouldn't bother worrying about it, especially if it means sacrificing readability or modularity.
StartCoroutine("<M>g__N|0_0")
telling people you can start local coroutines lol
oh no
Oh, I though they were talking about nesting calls, not definitions(local methods)
it is also possible i misinterpreted their question. but one of us is probably right
Whats problem with that?
I didn't explain completely clear my question was more about referencing stuff in a method from a method nested inside
I felt there was probably some crazy stuff going on to pull that off
You dont know how methods work?
local method i think, not calling other methods from method
that's demonstrated in the link i shared, actually.
the compiler generated a ref struct and the static method for that
just push/pop stack and change the pc in low level
Its not local, it needs to be static float/int/double...
still messing around with that to get a more realistic example but so far seems like it isn't a big deal
i also just realized i called the wrong method in the original link inside the N method. here is the fixed link that shows what is happening when you call that local method that accesses a variable inside the containing method
https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQMwAJboMLoN7LpGYZQAs6AsgBQCU+hxTAcnQNyNNHnqu2dcCSLsQC+A8cOIC0mCnwFCRRAG4BDAE7oAHugC86AAwcpImrRPLuFcwMF2r2sGEtXJTSaKA==
Ofc it isnt, depends on user how they want their code to look
I mostly put methods when i need to do some large calculus constantly
I renamed the stuff already since it was a bit confusing lol
yeah it's really not something worth worrying about tbh. any performance impact would be so small as to not actually matter for the most part. and if you have to micro optimize your code that much, you probably have other problems that you should be worrying about instead
yeah, thanks everyone
I was curious if this would actually work if you actually got the name of the compiler generated method. thankfully it does not so nobody has to try it ever again
https://paste.ofcode.org/ZnUguqYXnamz4FRMHQDufL
lol, did you check if it was actually named that using reflection/decompilation?
got the name through reflection
I presume Unity's reflection caching stuff doesn't capture compiler-generated methods like those
I would say that's good to know, but the only reason to know is curiosity ๐
Should a player health script call the game manager when its 0 or should it call the player controller and the player calls the game manager?
weren't you going to use an event for that? what happened to that?
Hi, what good methods would you recommend to read a .csv file ?
For now i thought about using StreamReader
also, my goal is to read this csv to make a jagged array. But I dont need to read & make this array each time I play. I just want to "convert" the csv to an array once in a while when I update the csv.
What would be a good "script writer" so i could "write" the array in my code or in another script, to avoid read & make this array each time I play ?
Hi ๐ Yes you are correct but I think I overengineered it a bit with Hurtboxes and Hitbox etc now I want to refactor it. Im not sure if it makes sense if health script emits event and the player listens to it and then emits another event for the game manager. This thing gives me ptsd or something ๐
i would go through player if player does stuff that gamemanager doesnt
What about the health script calls the player controllers "Die" method and the player then invokes his "Died" event + additional stuff (eventually)? So only one event?
ah na then i have the problem that its not really reusable for enemy again, sorry I don't know which rabbit hole im going down there
unfortunately unity can't serialize a jagged array so you won't be able to just read the file and write its contents to a serialized field which would have been the most convenient option.
if you really wanted to avoid reading it at runtime (which if you just do once at startup really won't impact performance all that much) you could do something silly like use some editor code to read the file, then write some c# code to another file that includes creating the jagged array using the data from the file as hardcoded values.
there's probably some other ways you could do this at edit time but i can't think of any off the top of my head
just make the player invoke an event when the OnDead event is invoked from the Health component
you could have some method on your player controller that handles its death animation (if applicable), starts any other death effects, and then invokes its death event that your GameManager is subscribed to
i was afraid of that, ty for the detailed response.
maybe i can do a in-between step ?
create my jagged array, make it to another format like json, serialize the json in a file (or field).
then at startup read this json (to avoid the writing of the array each time)
why. your data is already serialized as csv, right? so if your plan is to just deserialize it anyway just do it directly from that
Ok what about this:
Enemy and Player and whow knows who else, in the future have this interface:
public interface IImmortal
{
void Die();
}
The health script then has a reference to it:
public IImmortal body;
And the health script has this code:
if (amount <= 0)
body.Die();
The Die method on my Immortals look something like that:
public void Die()
{
// other stuff
Died?.Invoke(this);
}
i have to deserialize AND loop inside to CONSTRUCT the jagged array
so the csv is just the inputs to build the array
i can you give you an example if you want
Oh *** my english - it sthould be "Mortal" not immortal ๐
one sec, i know of a free asset that should be able to handle the csv. just gotta find it again real quick
my man
i still think you should use an event on your Health component. a UnityEvent can just be hooked up in the inspector. that way your health component won't have to worry about whether your object is mortal or not, it just cares about the current value of the health
ty
after some testing i realised that array can only have int as key, so i'll probably go with dictionnaries
Oh UnityEvent ok, I used normal events aka event Action.. - I'll look into Unity Event
this?
yep, or you could have kept using System.Action instead. this just allows you to subscribe to the event in the inspector
yeah i like that more that i can just subscribe from the inspector and dont have to create an instance in the PlayerController
When to choose one over the other?
just depends on your needs for the event. i'd give something like this a read to better understand how to use events https://gamedevbeginner.com/events-and-delegates-in-unity/
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hello, i tried making 3D controlle, and it seem to work, but it always move at same axis..
I multiply input with Vector3.forwatd but still doesnt help..
https://gdl.space/funitehoyo.cs
the answer is probably yes but do you already know if this library works well if double entries ?
- don't multiply velocity by deltaTime, you're just making it unreasonably small for no reason and requiring you to increase your speed variable a hundred fold
- use transform.TransformDirection to convert your input direction from local space to world space
okay, thanks
local methods are nice, as long as you're not passing it around it won't create new object
no idea
I wonder if local methods actually do calvirt under the hood or just the regular call ๐ค
oh and you weren't even using your input variable which is where you were actually multiplying your input by transform.forward and transform.right
UHH, i didnt saw that._. thanks
That was such a good read thank you very much, i think that answers all of my questions and thoughts
@slender nymph could I possibly get your input on this?
please don't ping people into your questions. also my answer is the same as this #๐ปโcode-beginner message
lets says i got a list of elements with a % chance
how would I do a random, and select the element ?
weighted random selection algorithm
Depends on how you want it to work. Do you want one item from this list to be selected, or roll for every on of them?
my goal is to retreive one, but i dont understand what you mean with or roll for every on of them
Since you have more that 100% total there, I thought there is a chance to get all the items at the same time.
i will change that, it will be a total of 100%
i forgot to say that the number were used as an example
real easy solution
make an array of 100 elements
add your different choices to the array the number of times the % should occur
random select from the array
making multiple array of 100 elements is maybe to necessary ?
this would mean thousands of elements later on for me
why would you need multiple arrays?
because i am doing selection using probabilities and previous results
idk how to explain, but, here is a example of a table, there will be maybe 1 or 2 sub(and sub sub) tables for each cells
with this screen only, this gives me 100 * 5 elements in 6 arrays
trivial if this is Enums of type byte its a miniscule memory usage
i didnt decide yet if im doing enums or string, prob enum
definitely enums, strings would be silly
yes
byte[100] * 6. Insignificant
so byte[100] here is a list of 100 enum ?
yep, if you declare your Enum as type byte
it's an array of bytes being indexed by x
ah okay, thought it was something else
how do I do that ?
public enum MyEnum : byte
if an enum is type of byte, what does it change compared to regular enum ?
a byte takes up 8 bits, if you do not declare a type the default is int which is 32 bits
so the array will take 25% of the memory
okay, but for basic stuff nothing change with the synthax of use of MyEnum ?
because i suppose there are cases where using int is usefull
of course not, the only difference is the number of entries the enum can have, if you use byte then that is 255
the only time I use anything other than bytes for enums is if I want flags, then I use ulong to give me 64 of them
I have these three Polygon Collider 2D components representing weapons being swung at an enemy.
I want to detect when the capsule collider on the enemy intersects this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
public class PlayerAnimationTriggers : MonoBehaviour
{
private Player player => GetComponentInParent<Player>();
private ContactFilter2D filter = new ContactFilter2D().NoFilter();
private PolygonCollider2D[] attackColliders => GetComponents<PolygonCollider2D>();
private void AttackTrigger()
{
List<Collider2D> colliders = new List<Collider2D>();
if (player.primaryAttackState.comboCounter == 0)
Physics2D.OverlapCollider(attackColliders[0], filter, colliders);
else if (player.primaryAttackState.comboCounter == 1)
Physics2D.OverlapCollider(attackColliders[1], filter, colliders);
else if (player.primaryAttackState.comboCounter == 2)
Physics2D.OverlapCollider(attackColliders[2], filter, colliders);
foreach (var hit in colliders)
{
if (hit.GetComponent<Enemy>() != null)
hit.GetComponent<Enemy>().Damage();
}
}
}
OMG, THIS WORKS ๐ณ
however...
I am concerned that Unity might be computing intersections of all 3 colliders with each other when an animation event triggers.
All colliders are set to "triggers", btw
maybe there's no reason to worry about that ๐ค
why did you revert to your original structure?
think about what
Physics2D.OverlapCollider(attackColliders
does every time you call it
the charater has a 3-hit combo and each sword swing leaves a different silhouette, hence a different collider
As I understand it, this will be called on exactly one frame and will check if the indexed attack collider intersects with an enemy collider?
(with no incidence filter)
it will execute the GetComponents every time, this only needs to be done once, in Awake
what? Why would it do that? I did that in line 8, I'm just trying to access the indexed element
because that is the way you have coded it, it does what you tell it to do
I apologize for misunderstanding your earlier solution
"GetComponents" is in line 8
Physics2D.OverlapCollider(attackColliders[0], filter, colliders); is below
you're telling me that just checking overlaps gets components from the GameObject?
Hey im an roblox studio dev and now im trying unity useing c# i feel like im the must dumbass ever i worked on sum for an hour then i didn t save it ;((
and is executed every time you reference attackColliders
any tips?
exactly what I said before, move the lambda to Awake
I will try again, but the syntax was wrong earlier
also as I said before, it should not be a lambda
I am still unclear, you are saying I should move the lambda to the Awake method, or that I should forego lambdas completely?
I should do straight assignment in Awake?
(that's not a lambda, that's an expression-bodied property)
wow, this is running like greased-lightning!
thank you so much!
i'm trying to make some angled springs for a platformer. for some reason if the player jumps into the spring without any initial horizontal velocity, the spring won't apply any horizontal velocity either. ie i have a spring pointing up-right. if i just straight up into it, only my vertical velocity is changed. if i have a tiny amount of left/right velocity, then the spring will apply the right directed part of the velocity as well. i'm using Vector2 testVelocity = (Vector2)(transform.up * springPower); and other.GetComponent<Rigidbody2D>().velocity = testVelocity; where other is the player from OnTriggerEnter2D(Collider2D other). why might this be?
I am so surprised about two things still (and it's alright if you have better things to investigate)
- why the lambda expression is causing the variable to redefine itself every time (fundamentals failure on my part)
- why I can define an array without specifying its size and do assignment to it in Awake(). Is this because I don't know how many elements there are during definition or assignment?
oh
well is it pulling from the components list every time?
re-executing its definition?
Properties are just methods, so you're just calling a method and doing the work repeatedly
the array question is simple, you declare the array, GetComponents defines it and returns the result
got it
thank you
wow, I thought for sure I broke my tutorial
but I actually improved it
(with your help)
trickiest part is anticipating what I should wait to see if he fixes later or what I should immediately improve myself
before it gets too coupled to other systems
(despite their best efforts not to)
this is a better-than-most tutorial imo
remember the old saying
'In the land of the blind the one-eyed man is king'
this is what it looks like. you can see it only boosts me horizontally if i already had horizontal velocity to begin with
Can you share more of the coffee?
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
{
if (other.CompareTag("Player"))
{
Vector2 testVelocity = (Vector2)(transform.up * springPower);
other.GetComponent<Rigidbody2D>().velocity = testVelocity;
}
}```
And are you modifying the character velocity anywhere else?
Ah, you're only setting the vertical velocity here
well, no. the spring is angled
it's facing up and right
and that doesn't explain why it applies the horizontal velocity only if the player already had an initial horizontal velocity
the only things that affect the player velocity are user input (wasd/arrow keys) and the springs
It probably does.
Can you share that code?
Probably your player movement code overwriting it
really you should not be doing this
other.GetComponent<Rigidbody2D>().velocity = testVelocity;
you should pass testVelocity to a component on the player and let that deal with it correctly
how does one do that
playerReference.DealWithIt(yeetVelocity)
well if you have a playerMovement class, use that, add a method that will take the velocity as a parameter and integrate it with you current player velocity
this was it i had something that would set player velocity to zero after damping caused it to drop below a very small threshold
single responsibility principle, break it and it will bite you in the arse every time
by single responsibility here, do you mean that if i want to change the player's velocity, it should have a method to do it so anything else that wants to change the player's velocity will call that?
yes, playermovement should only be changed by playermovement
i'll keep that in mind, thanks. not sure if that particular bit would have mattered in this issue here. i had
{
rb.velocity = new Vector2(0, rb.velocity.y);
}```
in PlayerController in FixedUpdate. my spring logic is in an OnTriggerEnter2D.
it would have done because you could have seen in one class that different things were affecting eachother
...it just dawned on me that if i wanted to set the velocity to zero after i was sufficiently slow enough i could have just checked the velocity itself rather than using an extra variable to check the previous position...whatever that's old code idk what i was thinking at the time. unless i actually did try that at the time and fsr it didn't work how i wanted 
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
whoa
My bad, i didnt know that i have to do this
yours clasifies as large
Hi Guys,
I needed some help with my AR project. In my project I have a Sling Arm and a Ball, one button when pressed destroys the hinge joint between the Sling Arm and the Ball, and there is another Reset Button when pressed I want it to put the arms back in original position along with the ball and the hinge joint between the sling arm and the ball should be reset. Unfortunately if I destroy the hinge joint, I cannot create another hinge joint between the two objects. Does anyone have any way to overcome this issue?
I have provided my code below, if anyone finds a solution to this, could you ping me or DM me as I really need help and am stuck solving this issue since some time!
Thanks!
why are you adding llsteners in Update?
When I add the listeners to the start function and run the project, the buttons don't work for some reason.... I do not know why this happens
well doing it in Update is a very bad idea so I guess you start with figuring that out
Okay, ill try to figure that out, but is there any way to solve the hinge joints issue?
yep,
HingeJoint hingeToDestroy = Ball.GetComponent<HingeJoint>();
if (hingeToDestroy != null)
{
Destroy(hingeToDestroy);
}
HingeJoint newHingeJoint = Ball.gameObject.AddComponent<HingeJoint>();
aint gonna work, you will need to wait 1 frame before creating a new joint because Destroy takes that long to run
Thanks, I'll try to fix this.
I'm struggling to set the sprite renderer color parameter via ternary operator
sr.color = white ? sr.red : Sr.white;
When I try this, I get an error that says can't implicitly convert bool to color
What type is white?
Color.white
Color.red
all the info you need https://docs.unity3d.com/ScriptReference/Color.html
also sr and Sr ?
sorry, I was uh...elsewhere when I typed that. This first line is what causes an error:
private void RedColorBlink()
{
sr.color = Color.white ? Color.red : Color.white;
if (sr.color != Color.white)
sr.color = Color.white;
else
sr.color = Color.red;
}
the if/else worked fine
I thought a ternary operator would be nifty
sr := SpriteRenderer
oh, no kidding
I see thank you
@languid spire private void RedColorBlink() => sr.color = (sr.color == Color.white) ? Color.red : Color.white;
๐
or ๐ฑ ?
fine, not the way I would do it but, fine
Are there any free/decent Analytic options out there?
DirectoryNotFoundException: Could not find a part of the path 'C:\Users\patbr\Downloads\testingGame_Data\Resources\Worlds'.
im doing this to get a folder but when i build my project it gives me this error: DirectoryNotFoundException: Could not find a part of the path 'C:\Users\patbr\Downloads\testingGame_Data\Resources\Worlds'. How can i fix this?
Missing Assets\ ???
when i input something onto a function does it make a copy of the the thing, or does it take the orignal? cuz i am used to c++ where you put an & to indicate that you want to put the orignal copy into the functions
~~i cant fix this issue, screen is located in a function
i dont even see how there is an issue, the var is delcared in same scope~~
forgot that i have to init with values
well, similar concept applies but you should research passing by reference and value types
ok but how do i control if its a reference or a copy
adding & gives me an error
you don't use &
yeah what do i use?
By default it's a copy, and if you want to reference it just use ref in the signature afaik.
ok thx
In a method signature and in a method call, to pass an argument to a method by reference.
How come it works in dev environment
But afaik this doesn't change anything when you pass it to a method?
Both reference and value types are copies by default to a function right?
right default behaviour is just passing the object without & as it's implied in c# if not value types
i need to edit an array inside a function
Knowing the difference is indeed a good idea for C#, I agree with that.
ref is useful when you do want to pass the value type in but not make a copy of it such that editing it inside of the method does not need to be passed back
yeah thats what i need, to edit the args inside the func
that path will not work anywhere, presuming your Resources folder is within the Assets folder
Arrays in c# are reference types you just need to pass them to the method and inside the method you will modify the original array
oh yeah true i forgot arrays are just addressess
It does work when testing but once I build it stops works
show the code where this is being used
I'm trying to rotate my player towards a target in the Y-axis using lerping. This pretty much works, but sometimes it rotates the 'wrong' way, as in, it takes the longer rotation over the shortest rotation. E.g: if clockwise would be faster to rotate, sometimes it still picks counter-clockwise. Anyone got any hints for me to fix it?
player.localEulerAngles = new Vector3(0, Mathf.Lerp(player.localEulerAngles.y, playerTargetY, cameraTargetRotationSpeed * Time.deltaTime), 0);
public static string WorldDirectory = Directory.GetCurrentDirectory() + "\\Assets\\Resources\\Worlds\\";
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
don't rely on eulerAngles from the transform, 99% of the time they are not what you think they are
so you recommend just using transform.rotation with new Quaternion()?
Quaternion.LookRotation doesn't rly work for me so I decided against that btw
ok, so this
public static string WorldDirectory = Directory.GetCurrentDirectory() + "\\Assets\\Resources\\Worlds\\";
is not this
C:\Users\patbr\Downloads\testingGame_Data\Resources\Worlds
is it?
it is for the build version
i also tried doing this and it still didnt work
public static string WorldDirectory = Application.dataPath + "/Resources/Worlds/";
what? it just randomly decides to drop the Assets/ part?
Hi, Iโm making 2D platofrmer, and I need help._.
To make movement Iโm using this:
rb.velocity = new Vector2(move*speed, rb.velocity.y)
But when I tried to make dash mechanic or smth like this by adding X force it just ignored it, so, what should I do?
well when i build it into my downloads folder it works and then when i create a folder in the downloads folder and move the files into there then it gives me the error DirectoryNotFoundException: Could not find a part of the path 'C:\Users\patbr\Downloads\New folder\Assets\Resources\Worlds'.
dont use Directory.GetCurrentDirectory() use https://docs.unity3d.com/ScriptReference/Application-dataPath.html
so
public static string WorldDirectory = Application.dataPath + "/Resources/Worlds/";
```?
use Path.Combine
Quick question really.... This is on a pre-fab which has a different name, how can I find the text UI which is within the pre-fab?
This is throwing an error
Or would an easier way be to find a game object with the name "PlayerIndicator"?
Although I will have 2 of them in the scene at the same time, so that Won't work
Yeah, I use legacy text componenets, I prefer them ahaha
ah I'll try this out
This didn't work either
Awesome, that worked well!
I was unaware that this existed.
public static string WorldDirectory = Path.Combine(Application.dataPath, "Resources", "Worlds");
i still get this error DirectoryNotFoundException: Could not find a part of the path 'C:\Users\patbr\Downloads\New folder\testingGame_Data\Resources\Worlds'.
How come if I use get component and an object doesn't have that component an error doesn't happen until I try to use that component
because it returns null
Because thats just how it works
I suggest just use TryGetComponent and check if it's null right then
TryGet returns a bool if the component is found so no need for a null check
right right
nvm i got a fix
float lerpedY = Mathf.LerpAngle(player.localEulerAngles.y, playerTargetY, cameraTargetRotationSpeed * Time.deltaTime);
player.localEulerAngles = new Vector3(0, lerpedY, 0);
So you can check if an object has a component
So if you navigate to
C:\Users\patbr\Downloads\New folder\testingGame_Data\Resources
in File Explorer do you see a Worlds folder there?
no
do you ever create one?
well its in my resources folder
The Worlds folder in the project is only accessible using the Unity Resources API, not the .Net File Api
how to freeze the camera to not going to z axis
If it's in your resources folder why not use the resources API to load them instead of using the file system
I added a collider to my object, but the bird still gets through it, I would appreciate any kind of help>>
he's writing as well at runtime, that's a no-no
How are you moving the object
ok so basically I was watching a tutorial, however, because of Im stupidity I forgot to add the part where he adds collision to the object
later on, I wanted to add by myself
I did add collusion2d
But the bird still gets throuh
gh
wdym
I mean how are you moving the object
in the scene, I dont have it
Don't have what
So if your problem is that you aren't colliding with the pipe the answer is probably because you don't have a pipe
I do have it in the gameplay
Can I call?
to be more specific
it spawns
like in the game of flappy bird
No
Okay so then how are you moving the object you've still never said
if u dont want the bird going through the pipes, then you need a collider on both of them and a rigidbody on the bird, and you have to move the bird in the code with the rigidbody (not transform.position or translate)
after it crosses the deadzone
I did just add the collider to the pipe
nonetheless, the bird still gets through it
what about the other things i said
How are you moving it
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Are both objects at the same Z position
I can see the z position of the pipe
However I cant see it for the bird
Furthermore, i cant add a component to it
usually in the bottom of the inspector scene
There is a box where I can add component
now there is none
ur just clicking on the image and seeing the image data for your bird. you gotta click on the bird inside the scene
Do you have your hierarchy window open? You should open it
No, I clicked on the bird image next to the birdscript
Show the inspector of the bird object
okay
i tried porting code from 3D, whats wrong?
2D raycast has different parameters than 3d, check the documentation for it
no. thats just your bird image
https://docs.unity3d.com/Manual/Hierarchy.html you need this. did you delete this window
Anyone why my serializable field is not outputting the Product from my script code
None of these are objects
Should I click on the birdscript?
These are assets
Open the object
i have a vertical fuel tank, and an engine at the bottom connected by a fixed joint and an upward force is applied to the engine. for some reason the thing starts tilting to one side after lifting off and after a few seconds it flips over. anyone know why could this be?
It was built by SpaceX ?
is the Center Of Gravity in the middle?
public float characterGravity = 9.81f * 2f;
However serializable field shows 9.81 still
Center of Gravity is calculated by the colliders
bird object
if they are offset to one side it will tilt
its a simple cylinder and cube at the bottom and they are perfectly aligned
did you change the code after creating the script?
I have saved the code and Unity should have applied the changes
are you sure they perfectly aligned? select both of em and check ur center pivot
Okay so it's at Z=0, and from your previous screenshots your pipes are not. Put the pipes at Z=0 as well
does not work like that, once a script has been serialized, the Inspector values take precedence over the code values
okay
The entire point of the inspector is for you to provide values that override the defaults from the code
I mean that was the default code
from when I first put it into a serializable field
If the code overwrite the inspector every time the code changed the inspector would be worthless for assigning values
okay
Yes and any new instances you add will have that as the default
This has nothing to do with you
It was literally a reply to someone else
im a complete beginner so i dont understand what those options do
Fixed it I removed and readded the component back to the Player GameObject, the 9.81 of default wasn't my original intention soo
thanks for the replies and help though!
Oh wait this si what you literally said lmao
increasing drag somehow fixed this
the bird stills gets through it
show what u got inside birdscript
okay
Im so confused
I did add the collusion
to the pipes
the bird still gets throuh
gh
maybe your collider is offset or something and its not actually on the pipe. if u click on ur pipe it should show a green outline for where the collider is. is it in the right place? and can you check the bird's collider as well?
okay
if u dont see it then u gotta click on "edit collider" maybe to see it
i can move them
from the scene
FINALLY
YEEEEES
IT WORKS
thx @polar acorn @cosmic quail
appreciate the help
how did u fix it? was it the colliders being wrong or what?
Oncollisionstay is a unity method you canโt just call it
I was trying to add colider to the pipe spawner
I had to add it to the pipe clone
to both of them
the upper and bottom one
Similar like void start update awake ontriggerenter etc
oh ok. glad you solved the problem!
Ait cool
sorry i mean the top pipe and the bottom pipe
ok
yup yup, makes sense
I'm sure it's something simple I'm missing , I have a float value that stays between 0 and 1. I try to add to the value while it's decrementing in a coroutine and It doesn't increase the value while it's decrementing
public void ModifyHappiness(float amount)
{
currentHappiness = Mathf.Clamp(currentHappiness + amount, 0f, maxHappiness);
OnHappinessChanged?.Invoke(currentHappiness);
}
private IEnumerator DecreaseHappinessOverTime(float durationInSeconds)
{
float startTime = Time.time;
float initialHappiness = currentHappiness;
while (Time.time - startTime < durationInSeconds)
{
float elapsedTime = Time.time - startTime;
float progress = elapsedTime / durationInSeconds;
currentHappiness = Mathf.Lerp(initialHappiness, 0f, progress);
yield return null;
}
// Ensure the final happiness rate is exactly 0
currentHappiness = 0f;
}
// Used with ui Button Like this --> happinessButton.onClick.AddListener(() => ConsumeHappiness(.05f));
public void ConsumeHappiness(float happinessAmount)
{
ModifyHappiness(happinessAmount);
}
I don't fully follow your question, but the coroutine is going to overwrite whatever value you get from ModifyHappiness if those happen during the decrease
Yes I'm trying to modifyHappiness during the decrement
I'm trying to add to it
The coroutine sets currentHappiness to a function that is dependent only on the starting value and the time elapsed
So this line is the culprit
currentHappiness = Mathf.Lerp(initialHappiness, 0f, progress);
Actually it seems more like the design is the culprit. You've created a system that decreases the happiness to zero in some specified amount of time, then you expect to add happiness after the fact. This is a contradiction - one of them assumes the drain happens in constant time, the other assumes it's at a constant rate, and they cannot both be true
You would need to either have the coroutine subtract an amount over however long it takes to reach 0, or you'd modify the time to reduce the drain rate
I was decrementing with a rate , like here
#๐ปโcode-beginner message
How do I disable a collider for a few seconds after exiting it?
make a reference to it , then a timer
coroutine is easiest
It's so I don't go back into it after jumping off the vine
Looks like this answer is what I would want
https://gamedev.stackexchange.com/questions/121749/how-do-i-change-a-value-gradually-over-time
what's that? never heard of it before
its just a way to make timed events
https://docs.unity3d.com/ScriptReference/Coroutine.html
A coroutine lets you run code that "waits"
Indeed.
eg
public Collider colider;
public float waitTime = 3f;
IEnumerator TimedEvent()
{
colider.enabled = false;
yield return new WaitForSeconds(waitTime);//wait 3 sec
colider.enabled = true;//enable it
}```
Note you need StartCoroutine to call it ๐
Where abouts would I need to put it?
whenever you want timed event?
so im making a auto scrolling platformer and I want the player to die if it gets to far to the left off screen, how would I get the camera's edges to place triggers right off screen?
Put a trigger area that moves with the camera and kills the player if they enter it
yes, but how do I get the camera's view's edges (the edges of the screen) and make that into world coordinates for the colliders?
I'd do it the other way around. Zoom the camera such that it fits the colliders.
Otherwise people with different aspect ratio screens are playing a different game
but if i knew the cameras edges, then the aspect wouldn't matter, because the colliders would always be at the edge?
2D Raycasts should interact with this edge collider, right?
You can get the frustum planes of a camera. https://docs.unity3d.com/ScriptReference/GeometryUtility.CalculateFrustumPlanes.html
yes, if your raycast actually hits it
@ripe shard I don't think I understand this documentation
Right- and the DrawRay should also stop at the edge collider, right?
There's 3 raycasts in this screenshot, and one of them isn't visible. It's unclear which one you're talking about. and no, there's nothing in there stopping the DrawRay at the hit points, they seem to be drawn to viewRange always
this looks like it should all be in a loop
instead of 3 separate nested raycasts
it is
I mean a loop instead of repeating code 3 times
well, I need to measure the distance and multiply said distance
if the raycast is going through a specific area in the game
right- is there a way to make a tag selectable from the inspector?
A custom inspector/property drawer with https://docs.unity3d.com/ScriptReference/EditorGUI.TagField.html
what is this, logically, supposed to be doing?
Or using NaughtyAttributes: https://dbrizov.github.io/na-docs/attributes/drawer_attributes/tag.html
I would like to stop at 15 degrees but it won't stop anyway and also if elevation is 0??
rotation.x is not what you think it is
Debug.Log
Well, since rotation is a normalized Quaternion, and elevation is presumably something higher than 1, it is impossible for this condition to ever be false
It is. Because if I go up the number raise up
it isn;t
Debug.Log(cann.transform.rotation.x);```
you will see
I did this to see it
I'm saying it raising up
What you see in inspector isnt what that value is
The inspector shows you euler angles
That is not fifteen degrees
That's one component of the four-dimensional vector expressing a specific orientation
I know but for example
This is inspector somehow Y raising up and X is still
Wait sorry
Cannon. My bad the X is raising with cannon
your whole approach to this is faulty.
do this:
if (Input.GetKey(KeyCode.W)) {
Quaternion target = Quaternion.Euler(elevation, 0, 0);
cann.transform.localRotation = Quaternion.RotateTowards(cann.transform.localRotation, target, cannonSpeed * Time.deltaTime);
}```
I want there to be a specific area in the game that is "harder" to see through, and I want to simulate this by measuring the distance between the target and whatever it wants to look at with a raycast
if the raycast enters/hits the collider of the specific field, then I want it to stop, and send out another raycast.
If it hits/reaches the target, then the distance will be tallied up, and the distance inside the area of the edge collider ( with the tag forest ) will be multiplied
if it instead hit the edge of the collider again, then I want it too tally up the distance with the multiplication, and repeat the function, now starting from where the second hit occured
Ok thanks it's working. I'll see tutorial about it
changed the code
my main problem is that the first raycast doesn't appear to interact with the edge collider, even if I have this enabled
or hell, the raycast doesn't appear to interact with anything for that matter
can't even hit normal colliders
If you have startPosition and endPosition then Raycast is overcomplicating things. You should use LineCast. It was made for that
Also you're drawing the ray with viewRange here but not considering viewRange in the raycast itself
because the raycast will only fire if the target we want to see is withing viewrange already
but I draw it with view range to reduce visual clutter
but you would want to actually limit the raycast to that distance then
otherwise the default raycast distance is infinite
okay sure-
but is there an error with the code that stops the raycasts from interacting with any collider?
presumably your ray is simply not intersecting the collider.
it clearly is
your code is checking for a specific tag
does that object have that tag?
if (hit) {
Debug.Log($"Hit an object with tag {hit.collider.tag}");
}
else {
Debug.Log("Hit nothing");
}```
yes
Try this quickly and see what it says if anything
where is my canvas going?
double click the canvas object in hierarchy
thanks
oh sorry i fixed it, turns out the canvas was a child of the camera
huh
I found the problem, the raycast was starting inside the collider
I assume that this shouldn't be happening
physics queries can be weird right at the boundary of the collider if you need high precision because then the little parameters make a difference
im atempting to create a script that can access another script to give a knife object some stats but im running into this issue and i got no idea how to solve it
Save your script
Hey, guys! I want to set a particle effect to my player, so whenever player transform changes to have the particle effect to the changed player position. How to do that?
make it a child of the player
Yes but where to put my Instantiate() because I am using instantiation for that.
It doesn't matter where you put Instantiate, but you should use a version of it that takes a Transform parent paremeter:
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Yeah I know that! I was using Object, Vector3, Quaternion I was wrong? I have to use that one you say?
This one has all that plus the parent param
Ok!
I do have a issue with my 3d game. when ever I turn left or right it will form a circle instead of going straight to left or right. Is there any solution?
yes, don't rotate
so I have a memory leak- any ideas on why?
I know its because of recursion/repeating the method inside itself, but I see no reason why it would repeat itself so much that there would be a memory leak
in this case, it should only repeat 1.5 times
Is there a best practise for where to store the level at which an item becomes unlocked? Does it belong in a Scriptable Object, in a dictionary, or maybe as a variable on the prefab of the item? Or just done to preference?
Dictionary with the item/type reference and bool should be fine
I would store unlocks as data separately from the item
Hello guys, i got some questions regarding declaring and initializing lists.
When declaring the variable
List<float> somelist;
we can initialize its content :
List<float> somelist = new List<float>();
// (1) i suppose this creates an empty list
List<float> somelist = new List<float>(){
10f,
4.5f
};
// (2) sets some values when init
but if i dont want to add some values right at the beginning, does doing some methods like varname.Add(item) error ? or will c# automatically construct a empty list then do the method ?
why would i do new List<float>() if i dont prefill ?
how I'd do that is up in the air
it could just be a single list of item-level pairs, or a list of "UnlockInfo" scriptable objects
Lists resize themselves.
They aren't fixed-size like an array is
yes, they double each time we go above its limit right ?
You need to construct the list so that it exists, though
you do new() so its not null
why isnt my particle system playing? its printing the print to the console, but i cant see any particles being played
An empty list is very different from a list that doesn't exist
ah okay, because sometimes i got no object references, i wondered why
so except if i SET the list, i have to construct it so its an actual list ?
note that this use of rotation is wrong
you should be doing transform.eulerAngles.x, etc.
If you want to use the list, you must ensure that you actually have a list
you could construct it in the field initializer, or construct it right before you use it
(and if it's serialized by unity, it'll be initialized to be an empty list, too)
ok ty guys
[SerializeField] List<int> foo;
List<int> bar = new();
List<int> baz;
void Start() {
baz = new();
foo.Add(1);
bar.Add(2);
baz.Add(3);
}
All three of these will behave correctly.
i see
It's possible that the system is getting stopped soon after it plays. Make sure that isn't happening
so [SerializeField] was the reason why sometimes it was throwing an error and sometimes no
(log when you call Stop, basically)
Yeah.
ty
Sometimes I initialize the list myself anyway
It looks a bit weird to see a list that I appear to never construct
that's just personal preference, though
thanks! in regard to the euler angles, i tried applying it to these circles, for some reason no matter what it just faces z
(in that case, C# will construct an empty list as the object comes into existence, and then Unity will overwrite it)
That could be an issue with how the particles are being rendered
I don't remember the specifics off the top of my head, but I know there are different ways to draw them
Also, make sure you have 3D rotation enabled
it wasnt turned on....
That'll do it -- the system was using the "Start Rotation" float field instead
can I ask here a question regarding the usage of a unity package ? (not built in)
or should i go in #โ๏ธโeditor-extensions
because its a code usage problem
i added a print to the stop function and it never got called so
idk whats happening here
#โ๏ธโeditor-extensions is for when you're making editor tools usually
Hi! Having trouble wrapping my head around quaternions. I'm just trying to rotate my cube either 90+- degrees in the X or Z world axis. But when i first rotate X, and then rotate Z, its being rotated in the local Z axis instead of world Z axis. I dont know how to get it to use the world axis here. I know the issue but not the solution.
The GetRollRotationX/Z just returns -90 or +90 depending on direction.
trying to use euler angles in isolation like that is a bad idea
you can't take 1/3 or 2/3 of the euler angles and reuse them with some other angle. They come as a set of 3 or not at all
due to gimbal lock
You'd probably be better off not using them at all
Yeah.. Been trying to solve this for three hours now lol. Im aware of the transform.rotate method but giving it the correct data on how much to rotate per iteration is difficult
Yep im aware of gimbal lock, thats almost whats happening,
the simplest option is usually:
Quaternion targetRotation = /* calculate target rotation as a quaternion here */
while (...) {
// blah blah
RotationObject.transform.rotation = Quaternion.RotateTowards(RotationObject.transform.rotation, targetRotation, Time.deltaTime * speedInAnglesPerSecond);
}```
e.g.
Quaternion targetRotation = RotationObject.transform.rotation * Quaternion.Euler(90, 0, 0); to do a rotation of 90 degrees on the x axis
Ah okay! I'll give that a shot, thanks ๐ I'll need to think about how to use my RotationCurve (animation curve) instead of the angles per second.
you would use Quaternion.Slerp in that case
instead of RotateTowards
if you know how to use it
@swift crag think i discovered the issue, put it in update and this is happening
Turn off collapse so you can see the order
So then yes it is stopped
what will help is to understand that you have to actually apply rotation operators
i dont understand why tthis happens, this is on a moving object that is travelling through the air
quaternion multiplication is equivalent to applying one quaternionโs rotation operator to another
It's happening because rb.velocity.magnitude is less than or equal to 10
but it shouldnt be, i dont understand why cus when i look at the inspector, it shows up as like 30 or 50
eg if you want to rotate by +90 in x, and then +90 in y, you cannot set new rotation to (90,90,0). Itโs just incorrect, and the order of rotations matters
Log the value
youโd want to take (+90 y rotation) * (+90 x rotation)
So you know what it is at that precise moment
just realised that it might be saying stopping because there are like 6 other items of the same type in the scene... now its constantly saying playing
speaking of gimble lock and quaternions, spent like a few hours debugging because I had to flip some quaternions from lefthand to right of my operator
and I still have no clue why
it's called "CodeLens" in the settings
is it in vs or unity?
VS...
alr
Well which program do you see it in
unity
Quaternion composition is not commutative!
Really? Show a screenshot of your unity window with that line visible

im being sarcastic...
i dont know why this particle system isnt playing, its filling all the requirements to start playing
Where do you set fast
right so-
i assume that the memory leak is occuring due to the recursion- but I have no idea why that would happen. Is it possible that the second raycast is spawning inside an edge collider?
im not getting any errors, heres the system if thats any help
this has nothing to do with your code. Those warnings are related to the job system/unmanaged C++ side of things
just restart the editor
Okay, so each instance of this script has its own particle system as well on the same object
correct, this is the prefab
And the particles are set to play on Awake, so what happens if you just disable this script entirely? Are the particles constantly playing?
doesnt seem like it actually, thats weird
So then it seems like either:
A) Your particles are playing and you don't realize it
B) Some other script is stopping them
If you select the particle system there should be a little preview window. Do you see them in that
its selected, cant see anything
Click that play button in the corner
it starts playing
Okay, so it is visible in the scene when playing
Here's an idea, comment out the line that stops the particles, and add this in update:
if (!fast.isPlaying){
Debug.Log($"{gameObject.name}'s particles are stopped!", this);
}
If this logs, then a different script is stopping the particles.
Well, it's not stopping but isn't that white swoosh the particle you're looking for?
no its meant to be these cascading circles
thats just a trail
Okay, so, since that debug isn't firing, then the particle system is playing. Select it in the hierarchy and see where the object actually is
I don't see the transform gizmo for this, is it where you expect it should be?
its because the particles are emitting from a single point, it is where its meant to be
That's what I'm trying to see. Is the Transform gizmo at the point you expect it to be
if i increase edge size it is there
Well, it seems to be playing constantly, nothing is stopping it, so my guess is it's just not visible from wherever you are looking at it
its just so weird because it does start playing and you can see it when there isnt any logic, i dont know what the hell is is happening ๐ญ
So you can see it with the script disabled?
yeah like it is emitting
Then it's probably the changes you've made to the particle behavior in code
The angles and whatnot
lemme comment those out one sec
Try commenting those out for now and just play/pause based on velocity
it only seems to start playing once it reaches around 10 for some reason
Well, that's the speed you told it to play at, right?
i wanted it to play when it was greater than 10
how do I make the scene show all layers?
Scenes don't "show" anything
They're collections of objects
well, this part of the UI
I can only see the gameobjects with the default layer
Is that object on a canvas
Also, if you can only see things on default that's a camera issue
The camera has a culling mask
in the game window its fine
So, I'm going to guess this is a misunderstanding of how canvases work. Are any of these objects UI objects?
Which ones are UI and which ones are non-UI?
None of them are UI
I just want to utilize layermasks for raycasts
Hey, guys! I have a question. Where we use BoxCollider2D and where the BoxCollider?
Show a full Unity window screenshot, with one of those white circles selected and its inspector visible
Are you using 2D or 3D physics
Why I am asking that because something happening when I am using BoxCollider2D on my 2D game and the player just falling down???
disable gravity
Hover over that box and double-press "F" on the keyboard
in the rigid body
@polar acorn There is no problem to use BoxCollider on my 2D game right if I dont want to use the BoxCollider2D right?
I've heard that 3D and 2D physics, which includes colliders, don't mix well
Are you using 2D or 3D physics
That is the only question
I don't know XD
if you're using 2D physics, BoxCollider2D
Otherwise, BoxCollider
You will never use both
How to understand which physics I am using ?
Is your game 2D or 3D
It is a 2D then I am using 2D right?
That would indeed make the most sense
i think im just gonna forget about this stupid particle thing
Can you show the inspector of this object's parent?
Yes, I just got confused when you said which I am using you know.
So, both of these have sprite renderers. A square and a circle. Did you want there to be two sprites?
yes
this is how I want it to look, but I need to change the layers of all the gameobjects to default
@polar acorn Hey! The same happening with Rigidbody?
Rigidbody2D doesn't have gravity option btw
Ah, okay, I had to poke around the editor a bit to find it, click this box in the top right
Like to enable and disable
Again, are you using 2D or 3D
that is the only question
oh yeah I see it
use the one for whichever one your project is
@polar acorn You said before to enable and disable gravity. In 2D environment a Rigidbody2D doesn't have that option to enable and disable that's what I mean. So, how can I enable and disable any gravity? Do I have to use maybe the Rigidbody itself and not the 2D one?
I didn't say to enable or disable gravity
You would just set gravity scale to 0
If you want your guy not to fall over, lock the rotation
Yeah that wasn't me
Sorry XD
@desert elm Why you said to disable gravity if there is no option for that in Rigidbody2D? Maybe you meant to use Rigidbody and not the 2D one like I said?
there is?
just set gravity scale to 0
Oh, you meant in code alright
Thanks!
hello guys, im using the unity free assets third person controller on android. but the ui controllelr camera movement is way too fast. how can i slow it down ?
This is driving me crazy and I don't know how to fix this.
I have my Player set up using Spine and I've set up the SortingLayers correctly and everything. For some reason though when I MOVE the character slightly, the Children GameObjects that have SkeletonData seemingly duplicates the Player's Head sprite, causing it to overlap the eyes/hair/hat
It only seems to be happening whenever the animation is set, which is why i crossed out the line for the Start method (I accidentally had Head Untoggled in the video but you get the idea)
What am I doing wrong here?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.

