#💻┃code-beginner
1 messages · Page 723 of 1
So I am simulating an engine and gearbox in unity. Clutch is sitting right between the engine and gearbox and it determines if the torque from the engine can pass into the gearbox.
The clutch has a value "clutchStiffness" the stiffer the clutch the more quickly it will disengage.
My gearbox script has a variable that im currently assigning int he inspector "shiftDuration" and valid values are between 100 and 500 milliseconds.
Anyone know a decent math equation I could use to make it so the shift duration is assigned based on the stiffness of the clutch? stiffer clutch = shorter shiftDuration?
I'm trying to drag the soup pot object, but it's moving along a weird axis (my camera is in orthographic view btw)
you want an inverse relation, so 1/x, or some a^x for 0<a<1, or you could use part of a parabolic curve, or you could even use an AnimationCurve to draw it out yourself
but yeah overall - pick some fixed points, specifically the max and min, and perhaps decide what "half" stiffness should translate to
or maybe make it linear, that's also an option
figure out what curve you want from there
then find an equation to fit the curve
public class DragandDrop : MonoBehaviour
{
Vector3 mousePosition;
private Vector3 GetMousePos(){
return Camera.main.WorldToScreenPoint(transform.position);
}
private void OnMouseDown(){
mousePosition = Input.mousePosition - GetMousePos();
}
private void OnMouseDrag(){
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition - mousePosition);
}
Animation curve is a nice idea, but I am trying to reduce the amount of values I have to adjust in the inspector and was hoping for an equation I could use where just making the clutch more or less stiff will reduce and increase the stiffness I think linear will be fine. But at least now I can look up some inverse relation equations and see what I can find.
animationcurve doesn't change the amount of variables, it just changes where/how you define the curve
This is the code I wrote to make it drag and drop
if i have multiple of the same component on one gameobject, can i create an array of them in the order they are listed in the inspector and if yes how would i do that? thanks in advance
The order is not gauranteed unless you manually drag them into the array (in the order you want) . . .
So, you can do it, just by manually adding them . . .
oh yeah thats pretty plausible
Guys, I lowkey want to make a game, but I'm completely new to this and could use some help.
please do not crosspost
Refactored your code to remove unnecessary component calls and to cache the display panel cards rather than accessing children.
- cardButtonPrefab is now a
CardUIrather than aGameObject - Removed the panel and instead provided an array of 4 for the explicit child slots
- Manage a list of buttons (
CardUI) instead of traversing from parent to children. - Decoupled button creation logic to be reused when refreshing display
https://paste.mod.gg/kldkparvpiih/0
the way i have my characters camera and direction set up, im pretty sure i can just make all of the movement options move him "forward", that way the direction controller bound to wasd controls which direction he goes, whereas asd is just making him move in that direction that points. is this a good idea? im shifting this from character controller to rigidbody + capsule collider
https://paste.mod.gg/ektlospthoyr/0 the code for the direction control
A tool for sharing your source code with the world!
i got a question how can i add a lock or unlock on the player input?
something like if you enter the area the player will be locked in place and cant move or look around
i cant find some similar ideas in the internet
new input system you should be able to just run , inputSystem.Disable()
Disable the locomotion script if you're using the old input system. With the new input system I'm not certain if you can just disable the entire controller. Guess it would really depend on your system and what you're wanting (should physics still apply etc)
If I get what you're saying, yes that is a common way to handle movement. A camera that just goes around the player but doesn't effect where the player is looking and wasd controls turning and movement
~~i just do a simple early return:
if(standBy)
{
return;
//else
HandleInput(); //or
HandleMovement();
}
```~~
handleinput will never run because it's in the if statement right?
same thing for the Camera Controller ^ that way i can have both ignore my inputs/movement
moveScript.standby = true;
camScript.standby = true;
if(standBy == true) -> the next line return will kick it out
wait.. somethings not right
void Update()
{
if (standBy)
{
return;
}
HandleInput();
HandleMovement();
}```
there thats the correct way ^
That's better
ya had a brain fart
I'm getting so confused rn. I'm trying to follow a tutorial and all of a sudden VS code won't let me type anything
how do I fix this?
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
Have you seen the problem that the mouse pointer disappears so in vscode/unity window the mouse pointer is invisible?
disappears? no I have not encountered that
It literally disappears and I cannot click anything anymore. Outside of the windows the mouse appears again
if it happens both in unity and vscode then something up with your setup
I managed to find the answer on a forum, all I have to do was press "ctrl+c" and then "i"
So I set a breakpoint, make Unity hit the breakpoint and the mouse disappears from window
no idea what that todes lol ohh thought you meant the suggestions werent showing.
oh no it just wasn't letting me type, apparently I had accidentally gone out of inset mode or something
When did that problem appear exactly?
Ok
I was just in the middle of coding and it stopped letting me type, I think I accidentally pressed ctrl but IDK
well I say in the middle of coding, I was following a tutorial, I have no clue what I am doing rn
just copying code, not learning much
i dont feel like its worth it to make a whole thread in code general but how the hell is this script printing out this value twice per frame? and at two different values?
there is no refrence to 100 anywhere and it works perfectly fine
I don't know what I should do to learn the language right now but youtube says to watch tutoorials on there
add this as second parameter on debug.log and see if there is another script calling (click log after it prints)
@rich adder do you know what I can do / where I can go to start learning C#?
to learn the language itself you should go through some c# basics. through some these types of resources
Microsoft Learn w3Schools
thanks but i changed nothing and recompiled and it simply fixed itself, what a weird bug
@rich adder giving the codecamp a try, so far it's going well
thanks for the help on getting started
do you know what kind of things I should learn from those websites? apparently you learn a lot when actually coding games as oppose to studying the language so I really want to get to that point quickly so I can begin to get a grasp of the language and make some small games
on w3schools link check all the stuff on the left.. pretty much most of those are "core" knowledge you will need, especially in game
syntax, variables, datatypes etc.
so should I just do all of them or are some more valuable than others?
ideally you should do all of them yes. You would be using those daily . No need to do all at once
ok well I'll do some today and then have a break so I'm not trying to cram it all in at once
thank you very much for all the help
why is there a value displaying as -3.7604e-05 in the inspector? its supposed to be a float whys the random e- in there?
Short hand for x10^ pretty sure. Means Exponent. So a big (or small) negative number it seems.
why does unity do that lol
just display my number
i need to copy the float into some code now and I am not sure what the value is
well really im trying to assign the default value. public float pex4 = -3.7604E-05f;
will that just work? it compiles
its scientific notation, which you should definitely learn in school
this value is incredibly close to 0, you could just assign 0
Yeah calc just outputs it as -0.000037604 (if I entered it right, the e-05 is weird)
So basically 0
Allocation of 66 bytes at 0000018AC05000D0
43 3a 5c 62 75 69 6c 64 5c 6f 75 74 70 75 74 5c C:\build\output\
75 6e 69 74 79 5c 75 6e 69 74 79 5c 52 75 6e 74 unity\unity\Runt
69 6d 65 5c 45 78 70 6f 72 74 5c 44 65 62 75 67 ime\Export\Debug
5c 44 65 62 75 67 2e 62 69 6e 64 69 6e 67 73 2e \Debug.bindings.
68 00 .. .. .. .. .. .. .. .. .. .. .. .. .. .. h.
Allocation of 66 bytes at 0000018AC0500070
43 3a 5c 62 75 69 6c 64 5c 6f 75 74 70 75 74 5c C:\build\output\
75 6e 69 74 79 5c 75 6e 69 74 79 5c 52 75 6e 74 unity\unity\Runt
69 6d 65 5c 45 78 70 6f 72 74 5c 44 65 62 75 67 ime\Export\Debug
5c 44 65 62 75 67 2e 62 69 6e 64 69 6e 67 73 2e \Debug.bindings.
68 00 .. .. .. .. .. .. .. .. .. .. .. .. .. .. h.
Allocation of 66 bytes at 0000018AC0500010
43 3a 5c 62 75 69 6c 64 5c 6f 75 74 70 75 74 5c C:\build\output\
75 6e 69 74 79 5c 75 6e 69 74 79 5c 52 75 6e 74 unity\unity\Runt
69 6d 65 5c 45 78 70 6f 72 74 5c 44 65 62 75 67 ime\Export\Debug
5c 44 65 62 75 67 2e 62 69 6e 64 69 6e 67 73 2e \Debug.bindings.
68 00 .. .. .. .. .. .. .. .. .. .. .. .. .. .. h.
TLS Allocator ALLOC_TEMP_TLS, underlying allocator ALLOC_TEMP_MAIN has unfreed allocations, size 198
Internal: Stack allocator ALLOC_TEMP_MAIN has unfreed allocations, size 198
To Debug, run app with -diag-temp-memory-leak-validation cmd line argument. This will output the callstacks of the leaked allocations.
...
My project is currently being flooded with these errors by the thousands and using gigabytes of ram
(just editor open, not playing.)
How do I destroy a prefab instantiated in one script in another script?
its for tire friction simulation code that is being executed 100 times each fixedupdate and setting it to 0 makes the car behave odd.
bro the last science class I took was like 20 years ago I am sure I did learn about it in school but this is the first time ive ever seen it since.
well if -3.7604E-05f is the value you need then use that value. You will likely start running into inaccuracies with float math when dealing with such numbers
so what e-05 just move decimal places to the left 5 places and add 0's where needed?
pass a reference of the prefab to the other script, or make some way to get the reference somehow
or is this just valid? public float pex4 = -3.7604E-05f;
the e part is just shorthand. so -3.7604E-05 is -3.7604 x 10^-05
0.00003456
How come you have to assign the actual number to it? Can't you just assign it through a variable that you've assigned to store the output from wherever you got the number from?
its for default values for a scriptable object
you dont need to calculate the actual value, as you said above #💻┃code-beginner message
it compiles
though i do find it incredibly suspicious this is the exact value you would need especially when dealing with floats
it might not be the exact value I need, but its code that relates to tire simulation. This value is from the slip curve of a real tire. Setting it to 0 makes the car behave noticably different. The software the tire manufacture uses may be using doubles not floats. but i am not getting any issues using the value so I dont its exceeding the limit for floating point.
If that's the value then that's the value 😄
if you start to use the value in a extremely long chain of float math, itll start to deviate from the actual result. but yea I dont know how you're using it.
a simple example of this: https://dotnetfiddle.net/RHsQSL
change iterations to a smaller or larger number and notice how it starts to just be wrong compared to doing 0.1 * iterations manually
Damn, even 7 iterations it starts to deviate
definitely being used in a long chain of math
no idea what the correct value to use here would be tho since 0 makes the car drive weird
How do you detect when a mouse drag has ended, like OnMouseDrag() but for when it is released?
i would just set a bool to true during onmousedrag then i would detect when the mouse button was released and if the bool is true set it to false and fire your code
So how would I go about getting a standard object (not a game object) to destroy itself? I saw something about an IDisposable interface, but I'm not completely sure it's what I want for this usecase.
{
//The idea is that this is an object that exists in a JRPG enemy's AI to help decide what action it should take and what target it should apply to.
//For instance, when a player party member attacks this enemy, one of these MemoryObjects is created with a threat value (the damage value of the attack) that attack accrued.
//Each memory (stored in a list obviously) is only supposed to last a limited number of time, though, and once that time is elapsed then the MemoryObject is meant to stop existing.
//I would really prefer the object internally decide when it should stop existing rather than an external source doing it, though.
public float threatValue { get; private set; }
float memory;
public MemoryObject(float threatValue, float memory, TimeEvent timer)
{
this.threatValue = threatValue;
this.memory = memory;
timer += Decay;
}
void Decay(float decay)
{
memory -= decay;
if (memory <= 0)
{
Debug.Log("A memory was forgotten");
//This is where I would call what ever function I need to call to delete this object entirely. I just don't know how to do that
}
}
}```
all you have to do is set the variable that is holding a reference to this object as null and the garbage collector will do the rest.
I tried doing that and it won't let me
elaborate
If I try "This = null" it tells me "This" is readonly
show me the code where you actually create the object via new MemoryObject
can someone help me w something
whats a unity VER file
and how can i use this >>> 876c10dd-339f-465a-aa58-23990e93d5e2
That shouldn't matter. The point is that the object is supposed to internally decide when to delete itself and not an external system
i mean it totally matters
var memory = new MemoryObject(); // persists until memory = null;
It matters if I want an external system to flag the object for deletion but I don't
ok you're not understanding what im saying
the only way to destroy this is by setting all variables that reference this instance to null
So I can't get the object to destroy itself then
not without unsafe code and manual memory management and changing it from a class to a struct no
This worked! Thank you
One moment I will send you a small example of your options.
there are interfaces like IDragHandler and IEndDragHandler which do this for you
what are you actually trying to do here? i dont see anything here that'd you need to forcefully dispose of. these are all just value types. the garbage collector will clean up objects that dont have a reference pointing to it anymore
you dont need to destroy it yourself. when something stops referencing it, it will be destroyed
public unsafe struct Foo
{
public void* ptr;
public Foo Create()
{
ptr = Marshal.AllocHGlobal(Marshal.SizeOf<Foo>()).ToPointer();
var foo = new Foo();
UnsafeUtility.CopyStructureToPtr(ref foo, ptr);
}
private void Destroy()
{
Marshal.FreeHGlobal((IntPtr)ptr);
}
}
this MIGHT work im not an expert with unsafe code.
this is so incredibly unnecessary and shouldnt even be a suggestion
Its the only way to achieve what hes asking for.
The idea is that I really don't want to have to communicate with an outside system (that being the list that holds the memories) if I don't have to. The idea is that these objects exist in a dictionary and, rather than the object telling the dictionary to delete it, the dictionary doesn't bother itself with if a certain object is supposed to be there or not because it's only ever looking at objects that are
if you dont tell the dictionary to remove it it will still be there though and you will get null reference exceptions.
so? this isnt a place where we suggest to do things in an abysmal way just because a beginner thinks it should be done this way
I suggested the correct way to him already but really bro every time you post you're just condescending. I suggested the correct way to fix it he didnt want to listen im not going to argue with him about why his design choice is flawed.
what
hi
then you should reconsider the design if the same objects are held in multiple systems. this just isnt how you should use c#
So this idea was doomed from the outset then. I figured this would work because I thought lists and dictionary would just remove null references automatically.
A tool for sharing your source code with the world!
anyone know what this is
It's not. It's only held by one system. I just don't want the object itself to be aware of that system if it doesn't have to be
I'm new to learning coding but I'm not sure where to start. Can anyone give me advice?
MemoryObject doesnt need to be aware of the other system at all. The other system just needs to remove the object from its list and it will be destroyed
try javascript/html on khan academy
there are pins in the channels
theres also a unity course somewhere
thank u
oh i was assuming coding in general
And I really don't want to iterate through every object every update to see if its time has lapsed yet
also can someone help with this
does setactive not work with instances
The only other alternative I can think of is having the object tell the list its time has lapsed through like an event or something and give it the information necessary to remove it from the list
i never said that was the alternative. you can use events and remove it that way
no matter what you do, the class holding the list needs to remove the MemoryObject from its list
theres no alternative
this might help
Ok so that IS what I'm going to have to do then
if u can access it
so now b... now that you took the conversation all the way back to where it was 15 minutes ago do you feel better?
and im still waiting for help on this
its been 5 minutes, plus you havent actually asked a question. no one sane is going to read this through random code to tell you what it is
oh i thought you linked to the message below that
sry
question: does set active not work with instances
first thing you should do is read the error that its telling you.
SetActive is supposed called on an instance of a game object, it also doesnt return anything
just started 10 minutes ago but idk if i did this correct i believe it makes the cube invisible
It should make it not just invisible, but remove its physical presence entirely
thats what i did tho
well not working for me tho
did i do something wrong
wait
was there a point to this or are you just trying to be rude? to answer your question, yes it does feel better because they found the actual design they should aim for and not using unsafe code
if i call an instance it doesnt return anything i assme?
It's going to sound insulting, but the only error I could possibly imagine in this instance is that the script isn't attached to something
welp you may or not be right completely forget about that
https://docs.unity3d.com/ScriptReference/GameObject.SetActive.html
SetActive does not return anything. thats what the void part means in public void SetActive(bool value);
look at the example on the docs i linked, it calls it on an GameObject
I mean all you do is sit in here being condescending to people all day i see it all the time. I figured thats just what we do here!
oh u meant that
Thanks
i just chatgpted it and turns out i was supposed to have a period and not an equals
im so dumb lol
🤷♂️ if you think trying to lead people away from awful advice is condescending, then sure im condescending. in the meanwhile ill continue to help others as I have been doing while you've been fed up on the fact they arent using unsafe code
To be fair, him telling me that the space in the list's memory was still going to exist and simply be null was helpful too. I was operating under the impression that lists would just automatically truncate any null objects
you should really consider doing some c# basics course, theres one pinned in the channel "intro to c#". itll help a lot more to know the language before trying to use unity
No bro I could care less if they used unsafe code. You caught the end of a conversation was rude and then suggested the same thing that was suggested 15 minutes prior to that when he was saying "I dont wanna do it the right way".you sit in here every day saying condescending shit. You got 400 pages of post in the unity discord and if we scroll through them you're being rude in most of your posts. Like dont you have something better to do than spend your time being an asshole to new programmers?
that was a rehtorical question you have 400 pages of posts we know you got nothing better to do. stop typing to me
👍 you're equally free to stop typing, dont keep talking shit and demand that i stop first. im sure you read through all 23k of my messages to come to this conclusion. I'll continue to help people as I have.
they clearly did not come to the conclusion of using events from your message then the suggestion that unsafe "Its the only way to achieve what hes asking for."
u can always block 'em and still provide ur feedback whenever u want.
bawsi's alright in my book.. but i have dozens of others blocked that like to gatekeep my advice..
nothings stopping u from keeping on keeping on
No, I did consider using events. I just really didn't want to since that would mean at least the constructor needed to see a system outside itself
I figured I could skip the need for that
And it appears I was wrong
MemoryObject doesnt need to know about a single thing outside
can you show how you set that up?
how do i fix this while still allowing jumping? if i jsut normalize it all it prevents jumping
It has to be able to see what ever function outside of it is deleting it since it can't do it inside itself
Otherwise what's the event that's flagging its time as having lapsed doing?
Does it not need a function connected to it to mean anything?
bro all anyone has to do is read throught he first 4 pages of your posts to come to the conclusion youre an asshole.
i dont know what functions or "it" is in some of this. itd be a lot easier to understand/demonstrate if you show the code
can anyone help me make it so where when I hold the button down to move, it stays moving? it is not working while I hold A or D down.
you'd have to show code to get help, also describe what "this" exactly is
in the OnMove function
i personally use 2 vectors
1 for my groundedMovement
1 for my airMovement
my airMovement speed modifier is nerfed
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
finalVector =
(groundVector * moveSpeed) +
(airVector * airSpeed) +
(Vector3.up * gravitySim);
characterController.Move(finalVector * Time.deltaTime);```
this is what i mean ^ bout #💻┃code-beginner message
that way when im not grounded my movement speed is about 1/4 of what i allow during grounded movement
thats my player movment. my game is about scaling so thats why i multiply stuff by the player scale
add logs and see when OnMove is running, itll be clear why you dont stay moving. You should just store the values you want in a vector, then set the velocity in update or fixed update
{
protected delegate void MemoryDelegate(StatBlock source, MemoryObject memory);
protected class MemoryObject
{
event MemoryDelegate onExpiration;
public readonly StatBlock source;
public float threatValue { get; private set; }
float memory;
public MemoryObject(StatBlock source, float threatValue, float memory, TimeEvent timer, MemoryDelegate removeMemory)
{
this.source = source;
this.threatValue = threatValue;
this.memory = memory;
timer += Decay;
onExpiration = removeMemory;
}
void Decay(float decay)
{
memory -= decay;
if (memory <= 0)
{
Debug.Log("A memory was forgotten");
onExpiration(source, this);
}
}
}
[SerializeField] float memorySpan;
//Instead of an int, I need a list of memory objects that decay over time and adding them all together creates a threat level
//protected Dictionary<StatBlock, int> threatDictionary = new Dictionary<StatBlock, int>();
protected Dictionary<StatBlock, List<MemoryObject>> threatDictionary = new Dictionary<StatBlock, List<MemoryObject>>();
public void AddThreat(ref StatBlock statBlock, int value) //Actually, I think I should let the AI decide how long it should remember things for
{
//if (!threatDictionary.ContainsKey(statBlock)) { threatDictionary.Add(statBlock, value); return; }
//threatDictionary[statBlock] += value;
}
void RemoveMemory(StatBlock source, MemoryObject memory) { threatDictionary[source].Remove(memory); }
public virtual void ExecuteAI(StatBlock myStatBlock)
{
}
}```
This is how I interpreted your solution of using events
im unsure on how id quite impliment that becuase my current system seems quite diffrent
you still have if(!isGrounded) right here...
you could have (two) different versions of ur targetVelocity
// step 1 decide base velocity
Vector3 targetVelocity = orientation.TransformVector(moveVector) * moveSpeed;
// Step 2: apply different values to target Velocity depending on grounded state or not
if (isGrounded)
{
targetVelocity *= 1f; // multiplier for clarity
}
else
targetVelocity *= 0.4f; // nerf multiplier
}
// step 3.. send it to ur move function
moveDir = Vector3.Lerp(moveDir, targetVelocity, Time.deltaTime * acceloration);```
is StatBlock the part you're talking about, where you dont want MemoryObject to have a reference to StatBlock?
With your current setup, AddThreat can create the delegate which calls RemoveMemory since it has a reference to the StatBlock and the MemoryObject.
the codes basically the same... (its arranged a bit differently but its all practically the same)
you get input -> you mix that with ur variables -> u send that to the function
adaptation big part of learning.. check examples.. see how they differ
try to figure out why they differ
try to see the outcome of the code.. regardless of the steps it takes
No. threatDictionary is. Ideally I would prefer that MemoryObject doesn't know about anything in AI at all rather than only having to know about RemoveMemory for the briefest of moments
so in this example u can pretend ur targetVelocity is 10...
in the if statement -> if ur grounded its 10 * 1 = 10 (normal)
if ur not grounded its 10 * .4 = 4 (slower)
edit: like directly from my script
https://paste.ofcode.org/WS6VupuAwjTMQwRZM3vEkp
if you look you can tell im just doing two calculations
1 for when im grounded and 1 for when im airbourne
its using the exact same Inputs but my speed multiplier and dampening modifiers are different
so depending on what im doing my Vectors are going to be FULL strength or they're gonna be HALF strength for example
I’m enrolled in one at my school
Although, if necessary, it shouldn't have to have a source either
Is this correct
well MemoryObject is a subclass of AI currently, but the only thing i see it having a reference to is StatBlock and TimeEvent. it doesnt seem to really know about AI at all otherwise. That delegate can just be changed to an Action<MemoryObject> if thats what you're referring to
correct in what sense ? if you mean you want it to to turn off as soon as it turned on, then sure
the else myName = Fred is kinda weird
= is assignment... ur setting myName to Fred on that line..
if my name isn't Jimmy set my name to Fred
the first if statement will always be true
that too
myName = "Jimmy";
if(myName == "Jimmy")
{
// myName is Jimmy
Cube.SetActive(true);
}
else
{
// myName is anything *but* Jimmy
Cube.SetActive(false);
}
``` makes more sense
It still needs a source to use as a key to look up where it is in the dictionary
Although I did not know you could cast actions that way. That is incredibly convenient
it dosent really fix the root issue however. it really just makes it worse to play. You still get launched on angled walls jsut much less becuase all slopes like stairs make you slow
angle wall launching? ohh i didn't know that was the main issue lol
yea, i wasnt considering that.. sorry
yeah i assumed being launched off the wall was clear enough of an issue
i thought u were controlliing it with ur Input
ah
soo i wasn't addressing the actual issue mb
soo the walls cause it to get launched?
yes. all slopes really
thats a new one for me.. (i've seen people get stuck on walls)
just the walls are themost angled and this the easiest to see
well i assume its becuase im still movinga t the same speed horizontally but a lot of that gets converted to verdical
but if i just force all speed to be normalized suddenly jumping is really bad
ohhh #💻┃code-beginner message and this is the current code thats doing that?
here is the video again
yes
and i dont wanan add a physics material to it becuase then id need to do it to cubes too and it still wont solve the root of the issue
ohhh.. ur setting ur velocity (directly).. not adding it..
when u run into an angled wall or slope its probably ur horizontal velocity being projected into the surface normal (just as u said)
i think its killing the "natural" physics of unity's physics system.. b/c ur overwritting
in your current code AddThreat still uses int, is it supposed to create a List<MemoryObject> then assign it in the dictionary?
if so, when you create MemoryObject you should be able to pass (memoryObj) => RemoveMemory(statBlock, memoryObj) from AddThreat
if not, this setup might still be a bit weird because of not having a correlation from List<MemoryObject> to StatBlock
if u use AddForce instead of overwritting the velocity it may work
like instead of setting the force / velocity directly you can take the velocity you desire.. and then subtract it from the force u have.. and that should be able to used in AddForce as a velocity change
Vector3 velocityChange = targetVelocity - new Vector3(rb.linearVelocity.x, 0, rb.linearVelocity.z);
rb.AddForce(velocityChange, ForceMode.VelocityChange);```
and something along the lines of "project along the ground"
i become an airhocky puck
Oh those were commented out. I did that mostly so I could set up the infrastructure so that I could get from an attack executing to the AI. I also realized this morning that simply having a direct threat value does not scale well at all late game. I remember wanting this sort of memory system before, but simply forgot about it completely yesterday
i remeber thats why i was setting it instead of adding
ok well that wotks but now i dont have gravity
ahh yes.. that means progress.. I think "every controller i've ever made has had a floating hockey puck" feeling rofl
u can probably keep track of gravity seperately.. and stick it into that target force before adding it
@eternal needle After having shuffled everything around it now looks like this
{
protected class MemoryObject
{
event Action<StatBlock, MemoryObject> onExpiration;
public readonly StatBlock source;
public float threatValue { get; private set; }
float memory;
public MemoryObject(ref StatBlock source, float threatValue, float memory, Action<StatBlock, MemoryObject> removeMemory)
{
this.source = source;
this.threatValue = threatValue;
this.memory = memory;
onExpiration = removeMemory;
}
public void Decay(float decay)
{
memory -= decay;
if (memory <= 0)
{
Debug.Log("A memory was forgotten");
onExpiration(source, this);
}
}
}
[SerializeField] float memorySpan;
//Instead of an int, I need a list of memory objects that decay over time and adding them all together creates a threat level
protected Dictionary<StatBlock, List<MemoryObject>> threatDictionary = new Dictionary<StatBlock, List<MemoryObject>>();
public void AddThreat(ref StatBlock statBlock, int value) //Actually, I think I should let the AI decide how long it should remember things for
{
MemoryObject newMemory = new MemoryObject(ref statBlock, value, 10, RemoveMemory); GameManager.instance.onUpdate += newMemory.Decay;
if (!threatDictionary.ContainsKey(statBlock)) { threatDictionary.Add(statBlock, new List<MemoryObject>() { newMemory }); return; }
threatDictionary[statBlock].Add(newMemory);
}
void RemoveMemory(StatBlock source, MemoryObject memory) { threatDictionary[source].Remove(memory); }
public virtual void ExecuteAI(StatBlock myStatBlock)
{
}
}```
is that not what im doing?
oh wait no the y is being set to 0
or no it shouldnt be
u could use its own velocity and let the physics do it..
normally atleast..
Why is this in the beginner chat
instead of 0 use rb.linearVelocity.y or rb.velocity.y if its the older unity
well im still fairly new to C# as a whole. i can write ome scripts but im not too knowlagbel on it so i presumed this was the right place
if you wanted to remove StatBlock from MemoryObject too, that's still possible with the way I wrote it above. but if you dont have a specific reason to remove it then id just keep it
ur fine.. basic movement / character controllers + simple rigidbody stuff is beginner stuff
no no I mean @eager stratus
The statblock doesn't need to be removed from memory. It's there just so that it knows what key to send RemoveMemory so that AI can find it in the dictionary
oh i see
someone using ref and event properly is no beginner to me
Because I was originally trying to figure out how to get objects to delete themselves which I thought was a beginner topic
by the way.. @past sentinel dont get discouraged.. having a good controller makes or breaks a game..
and it does take a while to get it worked out and working like u need it to
i've been working on mine for years now and its progressively getting better and better
but also the reason im not using the gravity thing normally on RB's is becuase i need it to change with scale
so take ur time.. make sure to understand how its working.. logging ur values.. all that good stuff
and just keep on keeping on
well questioning when objects are deleted in a managed language is also not a beginner thing
was this question answered?
u could still do that..
you could just add onto the .y with ur additional scaled gravity
and let the regular gravity still work
It was, yes. In the end it simply can't be done. I do, in fact, have to flag for something outside of the object to remove the one reference anything should have to it
not exactly sure how.. in ur setup but doable i believe
best to open a thread in #1390346827005431951 to continue but yes we have to wait for GC to delete most managed objects (bar stack allocated things and some other edgecases)
ya, that code gives me anxiety.. thats how i know its not beginner 👀 lol
the only things i can understand are the //s 🤪
https://paste.mod.gg/vzrydprtzocx/0
this is more of what I meant but yea that was under assumption you wanted StatBlock removed.
i notice i left ref statBlock in on line 35, mistake
ya, sorry i can't help much more than that..
even tho they are sorta related I do most of my work with Character Controllers.. soo
rigidbody controllers are outside my scope unfortunately.. except for the bare basics
for my becuase my game is a portal-inspred puzzle game the movement isnt that big of a deal as it would be for a more serious platformer but i do want it to be atlest kinda not bad
ofc.. understandable
i found that finding free character controllers like the one i wanted to build really helped me out
i would open them in a seperate projects and then take my time dissecting them.. (reverse engineering)
line by line.. figuring out how they do what i want to do..
then it was about adapting it.. asking questions about things i didn't understand.. following up by reading docs and stuff about methods i hadn't seen or used before.. and just attempting to piece it together
altho i will say.. u can still use ur rb.linearVelocity.y * scaleModifier but with a scale multiplier..
so its using regular gravity right... if ur scale modifier is 1 its just the same as it normally would be
if u had something scaled at 2 it'd be rb.linearVelocity.y * .5 or 2 depending on which way ur scaling..
and it still should work.. ur physics is gonna take care of the regular gravity.. and u just grab that value during the frame.. and add ur multiplier..
Vector3 vel = rb.velocity;
vel.y = vel.y * scaleModifier;
rb.velocity = vel;```
with that said tho
scaling doesn't affect gravity 🤪
a basketball and a bowlingball are gonna fall the exact same speed 😛
yes but it does look like it is
very true.. im just messing with ya 😛
but that is a trick
when objects are HUGE they appear to be moving much slower
i want physics to feel the same no matter the scale
soo like a Titan walking thru a city would use an animator thats slowed down..
so its solid in concept 👍
yeah and they feel floater becuase they dont fall as much while tiny ones feel like bolders
but i dont want that i want them to feel the same becuase consitansy is good to avoid confusion
(also i was curious if even AI could help. it could not)
well im kinda unsure of what the scaling is for then?
b/c they'd be consistent no matter what the scale
it could.. and it could not..
as long as u dont take every word it says as concrete data
and use a little critical thinking.. it can very well help talk it out with you and help u understand something u might be missing
heres the same cube at diffrent scales. I havent applies the gravity code to the cubes yet so as you see they look really bad
this is what was happining to the player too and you could quickly see why having what feels like 0 jump when small would be bad
I haven't been following but pesky air resistance makes things accelerate differently in the real world (see the feather + bowling ball experiment)
i was jsut yapping about why i scale gravity in my game
and its to make it feel more correct
even if it would be techniclly wrong
well there should be better means to reflect the real world better (if thats your aim)
i mean its a game. its about what feels good and to me it feels better to have a cube fall at the same speed regardless of scale
yeah in real life the tiny objects when you're tiny scaled will, from the perspective of a tiny boy, seem to fall more quickly than the large objects in the perspective of a large boy
and i can then use this for puzzles. small cubes fall slower so you can have more airtime to go into a door or whatever
I call it the "godzilla effect"
aye i like that ^
yeah and that makes sense but in my game i dont really want it to work like that
ive never thought of it from the perspective of a short or tall observer
interesting
but i guess i shove this issue back to the back burner becuase im still lost on any idea on what to do to prevent it
I actually may have misspoke - the size of the objects themselves and the absolute heights involved are the most important factor. The size of the observer really just determines the height from which you are observing.
ya i got u 👍
its not that big of a deal currently so
I am struggling to make the OnMove function work while being held. It only works once when I tap the key but movement keys should work while being held and I can't figure out how to get it to work that way.
i would reccomending using one of these
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
makes it easier to see
like this?
'''cs
//private void OnMove(InputValue inputValue)
{
rb.linearVelocity = inputValue.Get<Vector2>() * speed;
}'''
private void OnMove(InputValue inputValue)
{
rb.linearVelocity = inputValue.Get<Vector2>() * speed;
}```
I see
I am using the input system and I am struggling to make the OnMove function work while being held. It only works once when I tap the key but movement keys should work while being held and I can't figure out how to get it to work that way.
can anyone help me figure this out please?
OnMove is only going to be called once whenever the actuation of the input cahnges
if you want to do something every frame, use Update
you can store the latest input data in a variable here, then use it in Update
Well, FixedUpdate if you're using physics
Sure, it won't matter either way in this particular case
I believe I had something similar that looked like this
{
//Main serialize fields
[SerializeField] InputActionAsset actionMap;
[SerializeField] float moveSpeed;
//Component cache
Rigidbody rb;
//Misc variables
Vector2 moveVector;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
//Make sure there's a third person camera and that its subject is this
if (ThirdPersonCamera.instance == null) { Destroy(this); }
//Cache components
rb = GetComponent<Rigidbody>();
//Activate and link action map
if (!actionMap.FindActionMap("Player").enabled) { actionMap.FindActionMap("Player").Enable(); }
//Set up movement controls
InputAction movePlayer = actionMap.FindActionMap("Player").FindAction("Move");
movePlayer.performed += (InputAction.CallbackContext cc) => { moveVector = movePlayer.ReadValue<Vector2>(); };
movePlayer.canceled += (InputAction.CallbackContext cc) => { moveVector = Vector2.zero; };
}
// FixedUpdate is called once per physics iteration
void FixedUpdate()
{
if (moveVector != Vector2.zero)
{
float trueMoveAngle = ThirdPersonCamera.instance.transform.eulerAngles.y + Vector2.SignedAngle(Vector2.up, new Vector2(-moveVector.x, moveVector.y));
Vector3 trueMoveVector = new Vector3(Mathf.Sin(Mathf.Deg2Rad * trueMoveAngle), 0, Mathf.Cos(Mathf.Deg2Rad * trueMoveAngle)) * moveSpeed * moveVector.magnitude;
rb.linearVelocity = trueMoveVector + Vector3.up * rb.linearVelocity.y;
transform.eulerAngles = Vector3.up * trueMoveAngle;
}
}
}```
I'm not sure how to use the actual Input Action component. Honestly it's a miracle I even figured out what lambda functions do
so would I change the line to vector2 = inputValue.Get<Vector2>()
new to C# coding
then put that vector2 variable in the update?
I THINK that works, but only if it's in FixedUpdate or Update
you would make a Vector2 variable and do myVariable = inputValue.Get<Vector2>(); in OnMove and in Update you'd set the velocity equal to that variable * speed
what value does the inputValue.Get<Vector2>() return?
The way mine is set up, it only has to read an overhead Vector2 that has its value changed through lambda functions called in start
1 and -1?
it returns whatever you are inputting from your joystick or keyboard or whatever
It returns the X and Y vector of what ever your movement input is
W = 1 y
A = -1 x
S = -1 y
D = 1 x
also it's a 2sd vector so it's (x, y)
One thing that I found nice about the new input system is that it's not possible for it to have a magnitude beyond 1 like the old system
ok it kind of works
but now it seems the gravity of the object is off cause it falls down super slowly
and it seemed to have disabled my jump feature
but it does move left and right while the button is held
Depending on how you're setting the rigidbody velocity that can happen. For instance if you keep resetting the y to zero every frame
For movement you want both values. However you're generally applying them along the x and z axes with the y handling verticality (jumping)
rb.linearVelocity = new Vector2(horizontal, rb.linearVelocity.y, vertical);
^ u can feed the .y right back into it
therfor ignoring it (letting unity physics do its thing)
Yeah, I do that in my code too so that the move script and the jump script don't step on each other
@rocky canyon with my system do you know the ebst way to have my player stick to the ground when they are grounded?
private Vector2 playerInput;
private void OnMove(InputValue inputValue)
{
playerInput = inputValue.Get<Vector2>();
}
private void Update()
{
rb.linearVelocity = new Vector2(playerInput, rb.linearVelocity.y);
}```
this is what I have
not really.. i tend to do this
Actually, I completely forgot that 2d games were a thing. If your game is a 2d game then, yes, you should be able to ignore the y value of the player input and just use playerInput.x for the movement (You might want to modify it with a speed variable)
not sure that works with urs or not
in modern Unity you can also do:
rb.linearVelocityX = playerInput.x;```
so I would change the OnMove function then?
private void OnMove(InputValue inputValue)
{
playerInput = inputValue.Get<Vector2>();
}```
oh I got it work
thank you both for the help 🙂
What you could do is, instead of having playerInput as a Vector2, you could have it as a float and put
playerInput = inputValue.Get<Vector2>().x
instead
I used PraetorBlue's method and it worked
I put rb.linearVelocityX = playerInput.x * speed;
and it worked
i want all of my wasd to only move forward, in 3d, how should i go about that
reason being i have the way my direction is working already set up
what do you mean by "only move forward"?
like...just move forward in the direction the player is facing
you'd have to share your existing code.
but like
you want all of the buttons to do the same thing?
i dont have to worry about it, pressing D makes my character face right, and S makes my character face backwards
so if they move the direction they are facing then it should control it just the same
im moving from a character controller to a rigidbody + capsule
I believe a property you might be interested in is transform.forward
This appears to just return a vector in what ever direction the transform is facing
thanks, will read on it
how does that mean you don't have to worry about it?
Do you want D to make you walk forward or not?
You want S to make you walk forward?
Or do you only want W to make you walk forward
because when you say "I want all my WASD to walk forward" it soudns like you want all of those buttons to make you walk forward
It sounds like they want to use the vector to determine what angle the character's y rotation should be and then just use transform.forward for linear velocity
I'm pretty sure what they actually want is to move in the direction of the WASD vector but in relation to the direction the camera is facing
anyway it's going to be impossible really to answer this without seeing your existing code, as mentioned above
^
so if i press d, the character will turn right and then walk forward, therefore walking right
If they're anything like me then they haven't realized that the direction the camera's facing is something they need to factor in yet
you need to share your existing code
Either that or it genuinely doesn't matter because the camera's rotation isn't suppose to change
A tool for sharing your source code with the world!
So you've already got it here:
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
playController.Move(moveDir.normalized * plyMvspd * Time.deltaTime);```
But you have a problem - you seem to have both a CharacterController and a Rigidbody on this object
You need to pick one or the other
im replacing the character control with rb
thats the whole point of this, so i can use isGrounded
then you just do rb.linearVelocity = moveDir.normalized * plyMvspd;
and get rid of the CharacterController and all the code related to it
You'll also want to be doing rb.rotation = Quaternion.Euler(0f, angle, 0f); instead of transform.rotation = Quaternion.Euler(0f, angle, 0f);
as a rule of thumb if you have a Rigidbody you should never directly modify the Transform
Basically this: https://paste.mod.gg/rfqgookqqoyg/0
in the end im just trying to make a movement system similar to Sky: CotL
no idea what that is
Sky:CotL is c++ with a custom engine, i only barely know c# and unity so...
i can show a video though, have it currently installed because theres some ideas from it i want to test, like volumetric clouds
the camera does effect the movement im noticing, but ill figure that out when i get to it
looks like a pretty basic third person controller
adjusting your code as I mentioned above will get you part of the way there (it won't adjust for the camera rotation).
but as you said that can be added later
someone told me to use lerp on reddit for the non-instant movement when turning around and such
worry about getting it working first
true
But you're already using SmoothDampAngle
which will make it "non instant"
at least the rotation of the character visually
im having an issue with my character sliding across the surface, so they move extra when turning around
yeah the angle isnt instant, but the velocity is
did you add the else block like in my example code?
shit didnt notice it
I mean, your solution is what I'd do. I think that IS something I did once in fact
im just learning this so slow, i work 40+ hours a week and i have familial obligations
im trying to learn, but most of what i learn from is videos that poorly explain how the syntax works with the functions and objects
You're not really going to learn it if you're just copying code, you'll want to try to understand what it's doing
when you understand it you'll be able to tweak it to your liking
You may also want to spend some time learning C# itself if the language is giving you trouble
outside the context of games
i did the microsoft c# course for about a week
that's a good start
it's definitely going to take a bit before you're "fluent" though
but after a certain point it just felt kinda...console specfic? i guess. Like arrays and booleans and such are all useful, but learning how to make a folder through a terminal seems kinda useless for me..
true enough
im sure it has its application somewhere, like puzzle games that suddenly make folders appear on ur desktop but ya know
that aint me
regardless the syntax for calling functions and passing parameters and capturing return values and writing functions are all relevant
no matter what it is that the functions ultimately do
What I did was try to recreate Triple Triad while looking up every little thing on Google such as "how make object move in code?"
i mean when i see someone do vector3.something = new vector(smth, smth, smth ,smth, smth)
doesnt exactly look like the console.WriteLine they taught you for 4 modules straight 
i know its just gonna take time, but im impatient asf :(
Well yeah but it does use:
- Variables
- Constructors
- assignment
which are all things that they do teach early on
I presume they teach constructors at some point 🤔
anyone ever expirimented with brushmodel tires? got any links about them?
Hi, I wanted to ask about Animation Rigging, and I encounter this error about Burst Job abort. console error below. Does anybody know how to solve it?
System.InvalidOperationException: The PropertyStreamHandle cannot be resolved.
This Exception was thrown from a job compiled with Burst, which has limited exception support.
0x00007ffc9c78949e (Unity) burst_abort
ya, i tried to mention that yesterday
if ur going after the normal third-person movement style you totally need to incorporate ur camera into the code..
you can't really get the movement working without it..
unless ur talking about tank movement that would be if ur walking forward and press left at the same time it'll rotate to the left and keep moving forward (now to the left)..
-> once ur camera is involved it'd be totally different.. b/c if u were to pan ur camera around the backside of ur player now ur directions are all flipped
- TankStyle :
- Input is always relative to the player’s facing.
- Forward/backward moves along the player’s forward, left/right rotates the player.
- Diagonal movement results in combined rotation + forward movement.
https://hastebin.skyra.pw/tonurikuwu.csharp <- link to example code for the tank style movement (no camera involved) the rotation is similar to what u have now.. butW/Sor "Vertical Axis" would then move the direction its facing..
- Camera-relative third-person movement (modern 3rd-person/over-the-shoulder):
- Input is relative to the camera’s orientation.
- Forward always moves in the direction the camera is facing, left/right moves relative to camera right/left.
- Player rotation is independent and smoothly turns toward the movement direction.
- If you pan the camera, pressing forward could now move the player “left” relative to their original facing — the movement follows the camera, not the player’s initial facing.
c# unity iap, how to check if player already bought a non-consumable item?
https://hastebin.skyra.pw/vipeyefibu.csharp <- link to example code for the camera-relative style movement
the camera is not attached to the player (because if it was parented to the controller and you rotated to the controller.. the camera would also rotate.. and since we're using the cameras rotation it'd rotate more and more.. and u get in a loop.. instead we just make the camera track the player
something like:
Vector3 desiredPosition = target.position + transform.rotation * offset;
transform.position = Vector3.Lerp(transform.position, desiredPosition, followSmooth * Time.deltaTime);```
in the movement script - we use the `camForward` and the `camRight` to multiply our inputs with so when we pan the camera the general directions of the player change as well...
both example scripts.. Left one being (no camera -> Tank Controls setup) || Right one being (camera -> ThirdPerson Controls setup)
float collisionDetec(Vector3 movementDirection)
{
Vector2 rayDirection = movementDirection.normalized;
Vector2 origin = transform.position;
float rayDistance = speed * Time.deltaTime;
RaycastHit2D hit = Physics2D.Raycast(origin, rayDirection, rayDistance);
Debug.DrawRay(origin, rayDirection * rayDistance, Color.red, rayDistance);
if (hit.collider != null)
{
Debug.Log("Hit: " + hit.transform.name);
}
if (hit.collider != null && hit.collider.CompareTag("Collidable"))
{
return 0; // Block movement
}
return speed * Time.deltaTime; // Allow movement
}
ive got an issue where i want the ray cast to be in front of the player. the challenge is that the player rotates to face the direction of movement. how do i set an offset so that it is always in front of the player.
the player is a capsule set to scale x:1, y:0.5, z:1
// --- Offset the ray origin to be in front of the player ---
float offsetDistance = 0.5f; // adjust as needed
Vector3 origin = transform.position + transform.forward * offsetDistance;```
still centered on the player
lol
well
that di move it
transform.up was the one that did it
if i add more it will be perfect, thank you!
nice to see ppl using Debug.DrawRay to visualize these things 💪
Only other issue I think I’m going to have when it comes to cameras and player movement is I want to implement a lockon system, which means (I think) I’ll need a second camera to transition to, that orbits my player, but tracks the “lockon target”
But I’ll deal with that when I get to it

sounds like a solid plan tbh, esp if ur using Cinemachine
I have no idea where to ask this so I'm just gonna post it here but I'm currently taking the unity 6 official course and so far all the particle systems they have provided have caused these to appear, is it something to do with the particle system itself or just the particles from the project?
Some times an error saying "Invalid memory pointer was detected in ThreadsafeLinearAllocator::Deallocate!" also pops up every so often.
probably a bug / you can just clear them
restart the project.. i get them from time to time but havent seen any in a while..
Say I have Stack<ushort> is it possible to Take(32) from that stack somehow without looping?
unity 6.0? just curious as to what verison you're on. I had a lot of issues on 6.2.1 for the brief 30 minutes that I used it. as spawn said, its just a bug you can clear but the errors might get very annoying which id suggest changing versions if you were on 6.2
Does anyone know how Subway Surfer and Temple Run road spawning work?
there are tutorials out there, itd classify under "endless runner" when you search online
those 2 things aren't related
a Stack<ushort> contains ushorts
Take's argument is about how many values are taken
so you just get 32 ushorts out
32 isn't even near the limit of a ushort, not sure why you're asking about that
Ah I didn't know Take was a built in method for Stack<ushort> nah I just need to take a specific value out of the stack and was just wondering if there was an easy way to do it.
Ah I see
with linq you'd skip then take, but that's kinda not how a stack is supposed to work
perhaps consider if it really needs to be a stack
if it didn't I would use a list.
note that a FILO structure is easily implemented with an arraylist, so like List in c# would work
it has all the same operations and complexity (under different method names)
Ill give that a look now thank you.
6.2 is the version I'm on but this was also happening on the first version of unity 6
you use stack for wrong purpose if you want to take specific value from it
you most likely need something else than stack
What could be the reason that road material are not loading?:
material is made for legacy renderer and you are on URP/HDRP or material is for URP/HDRP and you are on legacy renderer
this is most common reason
if this is the case then the problem is with shader used for material
for simple cases there is auto fix if you are on URP/HDRP - one of last positions in "edit" menu at top of unity got material converter
Ok, thx, I will check
I wanted to follow up, does anyone know how to fix these?
the specific version might matter here. 6.0 is the LTS version so that will be safest, along with upgrading to the latest patch version.
though either way theres nothing here for you to solve. if these warnings/errors are consistent to the point of affecting your work then you should try a different version. I did see the same consistent warnings and error when experimenting in 6.2.1 so decided to go back
thanks
anyone knows is it possible to identify is user was host of the room that he leaved from photon webhook plugins in playfab cloud script?
anyone know about these bugs? happened whenever i try build as soon as i upgraded to unity 6.2 from 2023
fixed it
so i accidentally copied in a script into the urp script. i only noticed now two days after doing it. please can someone give me the script?
a script in assets?
huh?
ok, but is that in Assets or what
ok. whats confusing is i cant find it. i searched but it's not there. i keep getting this error tho thats opening the file
cool so yeah it's in a package
just reimport the package, or a similar option
no need to get someone else's version
Delete your library folder
And upgrade all your packages to the latest versions
damn, there's no option to just reinstall the package?
i dont have a library folder
it's not in assets
delete it via file explorer
@sage bronze you don't need to delete the entire library
in the packagecache, delete the urp module
theres loads of stuff in there do i delete the whole folder or not
it'll reinstall that module
The whole thing will be regenerated if you delete it
i have all these in packagecache. idk where it is
hmm. the first time i tried, a lot of things were regenerated but not everything
the second time, the package didn't regenerate
so yeah just delete the entire library
..the one named urp
but yeah no need, just delete the library
if you say so
Nice, I create a Desktop simulator with working window focus, taskbar items and animations.
And terminal window input and output logic 😎
{
[SerializeField] private CinemachineCamera winCamera;
[SerializeField] private GameObject winPanel;
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.TryGetComponent(out LetterCollision letterCollision))
{
GameManager.canPlay = false;
winPanel.gameObject.SetActive(true);
winCamera.Follow = letterCollision.transform;
winCamera.LookAt = letterCollision.transform;
winCamera.Priority = 120;
}
}
}
I dont know if here is the right place to ask. In my 2d game I want to focus on the transorm of my game object with my extra cinemachine camera that is specifically for zooming and following the target. I see the inspector and the follow and lookat targets assigned. However camera just refuses to follow or zoom on it.
https://docs.unity3d.com/Packages/com.unity.cinemachine@3.1/manual/setup-follow-camera.html
Check this out, it may help with your issue.
Incase you are unsure, the Z axis is what's used for zooming in and out 🙂
All right will do. Thanks.
It is such a great feeling when we spend many hours or even days of frustration over some things, then it becomes fixed and everything looks and works perfectly until the next issue right?!
Just hoping that my code isn't too much for what's needed. I call many instances back and forth.
Thanks I figured it.
Hey, ok it's probably an insanely stupid question but I can't seem to understand why am I getting this error with such a simple script can anyone with a working brain can help me out because mine seems to be in error 404 mode.
Im getting this error :
LevelNexter.cs(3,31): error CS0116: A namespace cannot directly contain members such as fields or methods
LevelNexter.cs(3,38): error CS1022: Type or namespace definition, or end-of-file expected
using System.Collections;
using System.Collections.Generic;
using UnityEngine;Collections.Generic;
using UnityEngine;
using UnityEngineSceneManagement;
public class LevelNexter : MonoBehaviour
{
public Player PlayerPrefab = null;
LevelSelector levelSelector = null;
void Start()
{
ListenSystemId();
levelSelector = FindObjectOfType<LevelSelector>();
}
void Update()
{
if (Input.GetKeyDown("n"))
{
Debug.Log("n key was pressed");
// levelSelector.SelectNextLevel();
}
}
}
Am I completely blind ? It looks like I have closed every bracket right to me, but I guess not if I get errors.
Sorry for the stupid question,
Cheers
It says the error is on line 3 (where you've made a typo)
Configure the !ide so that it highlights these things
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
The error is because you have a syntax error outside of the class . . .
It's telling you the error is on line 3. Look at the line to find the mistake . . .
column (aka character) 31
if you keep coding in light mode you'll be even blinder
Hey guys!
I was working on a project, but my code doesnt seem to work. Where do I ask for help??
I went through all the forums and did alot of research.
Yes Im usually in Dark mode but I just installed Unity back since a while for an old project and I didn't switch it yet 😂
but good call for sure
Post code errors and issues here. Make sure to explain what the possible is and how it is meant to work . . .
don't ask to ask. just post the issue
why does this not work?
double lastRefresh = 0;
List<string> refreshOptions = new List<string>();
for (int i = 0; i < resolutions.Length; i++)
{
double a = lastRefresh;
double b = resolutions[i].refreshRateRatio.value;
if (a == b) continue;
// refresh rate
string option = resolutions[i].refreshRateRatio.value + "Hz"; // might now need .value
refreshOptions.Add(option);
NewRefreshRates.Add(resolutions[i].refreshRateRatio);
lastRefresh = resolutions[i].refreshRateRatio.value;
}
``` it's for a dropdown of resolutions.
be more specific than "doesn't work"
use the usual methods, debug
the list is empty.
debug the stuff it depends on then
void moveToResource()
{
transform.LookAt(new Vector3(rDestination.x, transform.position.y, rDestination.z));
Vector3 moveDirection = Vector3.forward * jumpStrength;
moveDirection.y = 3;
rb.linearVelocity = transform.TransformDirection(moveDirection);
if (Vector3.Distance(transform.position, rDestination) <= consumptionRadii)
{
foodFound = false;
Destroy(resource);
resource = null;
hunger -= 6;
}
}
void searchForFood()
{
if (!foodFound)
{
float nearest = Mathf.Infinity;
Collider[] hitColliders = Physics.OverlapSphere(transform.position, vision, 8);
GameObject nearestPlant = null;
foreach (var plant in hitColliders)
{
if (Vector3.Distance(plant.gameObject.transform.position, transform.position) < nearest)
{
nearest = Vector3.Distance(plant.gameObject.transform.position, transform.position);
rDestination = plant.gameObject.transform.position;
rDestination.y = transform.position.y;
nearestPlant = plant.gameObject;
} else {continue;}
}
if (nearestPlant is not null)
{
resource = nearestPlant;
foodFound = true;
}
}
if (counter <= 0)
{
counter = timeTillJump;
moveToResource();
}
}
so this is attached to a bunny rabit, when its hunger raises to a threshold it starts searching for food, when it finds it moves to it and consumes it, the problem i am having here is the resource variable is not getting set and hence the carrot isnt getting destroyed, so basically the rabbit is just farming the same carrot for infinite food.
The rDestination is being set
that is not null is questionable
idk, the ide recommened me to do that
yea don't think you can use that on unity objects can you ?
did you read why?
it doesn't make sense here
wouldn't you want to check for that in the foreach loop anyways
check what?
you can, just does a different thing
check that it's a valid object
though.. i don't think it'd be in the colliders if it wasn't valid
(btw, the else continue; is unnecessary)
perfection 😅
redundancy
removing it
you put gameobject layerNumber in overlap that seems wrong, since it wants a Layer mask
its weird cause they are just checking for any collider in that layer, but no a component check
what layer is the carrot on
layer 8
well then yeah the layermask thing is wrong
layerIndex and Layermask != same
int layerMask = 1 << myGamObject.layer;
or
LayerMask mask = LayerMask.GetMask("whatever");
so I do ```csharp
LayerMask layer = LayerMask.GetMask("Plant");
you should have it serialized tho tbh so you don't have to work with the magic string
or just like you know make a field
okay thanks shall do
what
correct (don't forget to set it in the inspector :P)
ok in my settings script i auto select the correct index for my dropdown but for some reason it's out of range?
int val = 0;
for (int i = 0; i < resolutions.Length; i++)
{
int a = (int)resolutions[i].refreshRateRatio.value;
int b = (int)Screen.currentResolution.refreshRateRatio.value;
if (a != b) continue;
// resolution
string option = resolutions[i].width + "x" + resolutions[i].height;
resOptions.Add(option);
NewResolutions.Add(resolutions[i]);
if (resolutions[i].width == Screen.width && resolutions[i].height == Screen.height)
{
currentResolution = val; // was i
}
val++;
}
what's out of range
which line
shouldn't have to play detective lol
sry it's the current resolution. i really should get better at explaining my issues.
where ? I dont see that current resolution accessing an index
paste the line thats throwing out of range
no, the dropdown is using the current resolution.
resDropdown.value = currentResolution;
bro that's not even in the snippet you gave above LMAO
I dont even see it in the code
int val = 0;
for (int i = 0; i < resolutions.Length; i++)
{
int a = (int)resolutions[i].refreshRateRatio.value;
int b = (int)Screen.currentResolution.refreshRateRatio.value;
if (a != b) continue;
// resolution
string option = resolutions[i].width + "x" + resolutions[i].height;
resOptions.Add(option);
NewResolutions.Add(resolutions[i]);
val++;
if (resolutions[i].width == Screen.width && resolutions[i].height == Screen.height)
{
currentResolution = val; // was i
Debug.Log("Yay!"); // this does get run
}
}
resDropdown.AddOptions(resOptions); // this is filled
resDropdown.value = currentResolution;
resDropdown.RefreshShownValue();
why not just send the entire script properly via links so we know what the hell each variable is lol
sry i just thought it would be easier also i don't know where i would get a link.
its easier for us to scroll through an entire properly posted script than asking questions from bits and pieces just to get the full thing anyway lol
!code 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A tool for sharing your source code with the world!
it isnt working still
Debug.Log the hit items (in the loop if you want) and see what are the objects that it catches, start from there so you can verify its what you expect
the funny thing is i tried that, the log got skipped
but i did that for the resource variable
currentResolution should be for resolution dropdown not refresh rates?
this is why tracking two arrays like this can be confusing
yeah but that's not where i'm getting my error.
you said line 48 ?
ig thats an empty array?
no it means there is in fact an array.
If you want to know the contents put logs in each iteration or use myArray.Length for just the Count (wont be much more help than just printing the hit cols)
yes line 48 i have it as two lists (not arrays) for simplicity. as resolutions has all resolution types including refresh rates, so i make it so that the first has all the resolutions with the same as my monitor, and the second it'll just add a new refresh rate when it sees one.
issue is probably in SetResolution
that weirdly enough works perfectly fine. as i said in's in line 48
foreach (var plant in hitColliders)
{
Debug.Log(plant);
if (Vector3.Distance(plant.gameObject.transform.position, transform.position) < nearest)
{
nearest = Vector3.Distance(plant.gameObject.transform.position, transform.position);
rDestination = plant.gameObject.transform.position;
rDestination.y = transform.position.y;
nearestPlant = plant.gameObject;
} else {continue;}
}
the log isnt logging anything
it doesnt work fine if you're assigning the wrong values lol
cause if you retrieve the wrong index for the list then your issue comes up
slight nitpick from before also, Lists are just arrays that can expand
im leaking memoruy with the particle effect system
if log is not printing then you don't have items in the array.
try printing the quantity before loop
using UnityEngine;
public class Distance_Script : MonoBehaviour
{
private Transform parentTransform;
void Awake()
{
// Cache the parent transform once
parentTransform = transform.parent;
}
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
if ( transform.position.y <parentTransform.position.y -11)
{
Destroy(gameObject);
}
}
} ```
the indexs are fine there it's just in resDropdown.value = currentResolution; as there's some de-sync probably.
not using layermask
i created variable, didnt use it
is there anything wrong ?
how do you mean
using it also, nothing changes
but why....we established eariler..You cannot pass a gameobject index... they don't correspond to layermask
but now that i changed it, nothing happens
Collider[] hitColliders = Physics.OverlapSphere(transform.position, vision, plantLayer);
it is set in the inspector
could you show that is set in the inspector and the collider you want to hit has that layer assigned
currentResolution is larger than resDropdown
as I said, the indeces don't match
you're off by about 1
look over your code again careful and you will see. I can't do a full view rn cause on mobile but you can verify
and i agree, as i said there's probably a de-sync somewhere but what confuses me is that if i manually set it to 0 it doesn't work.
resDropdown.value must be between 0 and resOptions.Count - 1
I think its where you do val
increment val after assigning currentResolution
carrot has no collider ?
then how is overlap supposed to hit it 🥲
oh! it happens everytime i change the resolution. i know you said about it before but the error didn't point to it.
its unity's fault for not undetstanding my needs 😅
box collider trigger should work right
yeah any collider but if this is 2D colliders you need Physics2D.OverlapCircle
oh its 3D. then yeah you're good nvm
well then how was the rDes being set
Unity is the worst commercial game engine on the market but even then that's 100% on you
did you hit your head ?
I didn't. Unity has been release half cocked partially finished features since unity5
it being the "worst commercial engine" is definetly not me
whats rDes again ?
it is the destination of the resource (food here)
No you expecting Unity to know your needs instead of telling it what you want is tho
I mean sure some stuff got axed but "worst commercial game engine" is a stretch
send code again via link
it was a joke, so yeah
on mobile its easier to see it in a dedicated code paste site and discords awful code embed
the whole file?
just wanted to see the rDest part you asked about
whole is fine
@rich adder https://paste.mod.gg/oabbkxfiakfp/0
A tool for sharing your source code with the world!
also it was the filter probably looking for layers on 3 ? I think it was 3.. so anything wiht a collider
i havent implemented that part yet, it is water layer, thirsts on the pending table
will change tht
Dots has been out for years. Still no built in animation system. The engine is on its 5th version of multi-player libraries. They come out with all these new features that are half finished with incomplete tooling. It took until Unity 6 to get rid of random progress bars that would halt your work for 3 to 5 minutes. There are a ton of community implemented features that most engines have built in for example world streaming and imposter systems. I can't think of any other commercial engine that has these issues.
Don't get me wrong I do like Unity but there are so many issues that other engines don't seem to suffer from. There is a reason most studios favor unreal and imo it's because they know every feature in the engine is going to polished complete and have 100% of the needed tooling put of the box
but unity is kinda intuitive, getting things started
i tried godot, didnt understand a think
I mean some points make sense, and I do share some furstrations, but if it was the worst it probably wouldn't be the most popular engine lol
unreal, well thats for nasa engineers
It's not the most popular engine for people actually making full games
doubt .. is that why big triple AAA studios still use it ?
one very popular game. Marvel Snap.. all unity
the list goes on
You honestly gonna try to argue that unity gets more use than unreal
you can take any top 10 games and 8/10 probably unity
and probably 0/10 care if we argue guys 😅
Unreal runs like shit, but big studios dont care because they dont have to pay money to mantain their own engine anymore
@languid pagoda, might be the worst but stillgets people into game dev, and thats enough no?
..anyway no point of arguing about it anyway, it makes no difference what we think in the grand scale of things.. Use whatever engine fits your project and move on.. the end result is the only thing that matters
Unity gets more use out of hobbyists. Unity has 2 successful titles that I am aware of tarkov and marvel both of those games had to implement major systems to accommodate for missing/incomplete/non performant systems
no matter where i increment val it still doesn't work.
and people getting into the hobby is great
But I prefer Unity myself I like it better but these are the types of discussions that need to be had to make the engine better
bro you're talking nonsense here...Rust, Among us, Heartstone, Cod Mobile, these are not indie..
either companies use in house or smth commisioned, so laymen like us are more important
Studios are also relying on frame generation to make up for poor optimizations it's not an unreal issue engine runs fine in games that are properly programmed
In house is becoming more expensive to maintain and R&D , hence big studios switch to UE sadly , most engines are C++ so its easier to go to unreal
unity has 56k games on steam, unreal has 17k
isnt Ue in house itself?
and all the successful indie games that i know are made in unity
Unreal Engine used to be the major Engine for Unreal the game, then it become Fortnite / R&D for both the engine and game
That number is meaningless when there are literally asset store assets released on steam with no changes
same is done in unreal though
sounds like you have a personal vendetta thats clouding your facts
what if unity is bad and ue is good? nothing changes will it
I have no vendetta I prefer unity over unreal for how simple the editor is. But it doesn't change the fact over the years I've had to implement features that should be in the engine out of the box
I get it, I'm hurt we still dont have CoreCLR while unity is pushing AI bullshit...I dont disagree that they have poor management but the engine itself...thats another story
maybe I just dont have that experience so I cannot speak on that part.. I cant say I disagree, just by the earlier "worst commercial engine on the market"
We don't even have a proper way to implement decent vehicle physics. We have a half exposed physx wheel collider from like 2008
what about Havok?
isn't ECS Physics supposed to be a custom built physics engine as well ?
you have 2 other options no?
Havok is probably one of the best out there..
If you want good vehicle dynamics in your game get ready to write your own suspension with raycasts and your own tire friction code using brush model or pacejka formula. Meanwhile unreal engine has simulation grade vehicle physics out of the box
make a value, subtract value by time
should i make it out of plane or smth else
It doesn't have built in wheel colliders
well okay I give you that..but doesn't make it better imo but again we go on personal feeling/opinions, nothing more
but on the other hand there is also stuff in unreal that you have to write yourself from scratch in c++
and nav what would you recommend, hunger based system like this, where you eat you survive or something like energy based system
That unity has out of the box?
the amount of "out of the box" they need just to keep up makes sense
Input system on Unreal was dog shit, it is compared to new Unity Input system.. I see unreal has finally copied a similiar system
maybe, but making it from scratch in unity is way easier than making it from scratch in unreal (especially when blueprints wont cut it and you have to delve into the undocumented c++ code)
I mean unity went what? 5 years with no officially supported multi-player solution as well
depends on your game . I'd prefer old school hunger/thirst
Angelscript is also a thing
its just a sim
You don't have to jump into c++
what happen to Verse 😂
No idea what that is lol
apparently was a new language for Fortnite UEFN / Unreal that was supposed to get implemented into Unreal itself
https://dev.epicgames.com/documentation/en-us/fortnite/verse-language-reference
old school as in? depletion without considering activity?
Dayz has the best hunger thirst system I've personally seen
i am making an eco type sim
no i mean Thirst and Hunger, so you eat certain items especially charred ones your Thirst goes up
player is just an observer
This may still be in the works no idea its been a minute since I've last used unreal
looked promising , esp not having to deal with C++ but I kinda hate these engines going the "pythony" route..
DebugDraw.DrawBox(vector3{Z:=150.0}, rotation{}, ?DrawDurationPolicy := debug_draw_duration_policy.Persistent)
https://dev.epicgames.com/documentation/en-us/fortnite/debug-your-game-with-debug-draw-in-verse#box
like bro.. what is this sytax lmao
I don't understand why no one has implemented the pawn scripting language into a game engine. It's data driven, has one of the most efficient memory models on the market and its a small simple language that doesn't lack features and has been being used since the early 90s in microcontrollers
yeah I never even heard of it so it makes sense in the grand scale of things, hiring a bunch of C++ programmers is easier to find than pawn scripters
I have embedded it into unity in the past and it executes code just as fast as c# without any memory bottlenecks
Not really it has a c syntax anyone who knows c c++ or c# could pick it up in a couple hours the language used to be called small c
yes but I suppose there is a reason it never took off. I'm not technical enough to know those so I'm not sure.
Make your own engine with it 
Oh I'm good bro I already embedded it into unity. It has a ton of use in game modding. San Andreas multi-player mod features 1k player servers that ran well and all the game modes were made with pawn.
A lot of the reason why it never caught on is because it's advertised as a 32 bit language but it's as simple as changing one definition in a header file to make it work for 64 bit systems
Essentially pawn compiler would calculate all the needed memory for the scripts and then the runtime would then allocate it all up front in one linear block that made the cpu really happy
It's an awesome little language though. The ide even has a full debugger like visual studio with breakpoints etc
Is this related to source pawn
I'm really struggling to figure out how to create a weapon system where the player can switch , drop and pick up weapons. Does anyone know any good tutorials that go over that? I'm struggling to find one
What part are you struggling with?
The biggest thing is to make sure you have properly separated the three incarnations of the weapon:
- the version of it in the game world
- the version of it in the inventory
- the version of it it when you're actually holding it
It's best to keep these distinct from one another
character now moves forwards based on camera orientation. Sprint no longer works, despite rb.velocity being tied to plyMoveSpd, it seems as though the speed the rigidbody can move is capped around 5-10f. 50 makes barely a difference compared to 5. I want to set up sprinting, but if the speed is capped like this i wont be able to do what i want. https://paste.mod.gg/ttmjkoonrpoy/0
A tool for sharing your source code with the world!
It is related to sourcepawn and amxmod yes but they edited it so much that it basically just the syntax is similar
idk much about sourcepawn i just know the interpretter they made is not as performant 🙁
Thought as much. All these scripting langs are cool but doesnt help learning em when a new one exists each week
sourcepawn is alright but tbh all I have done with sourcemod has been c++
which they neglect
I have a pawn abstract machine written in asm that is called to from C# it runs game code so good. The only real annoying this is that objects do not exist, so I have to keep dictionarys of objects and pass the key to pawn as an "ID" so to speak.
still works fine but can be annoying when exposing new systems to the scripting language
....fixed somehow? I dont know how i just changed getkeydown to getkey...and all of a sudden the speed cap was removed?????
I think getkeydown is only called on the key the frame was pressed
so yes that makes sense
Interestingly enough sourcepawn has a similar issue thats half fixed and you have some interaction with sp objects from cpp when your native funcs get called
Can I add a Transform of a gameobject inside a prefab into a Scriptable Object?
You need to ref the prefab asset
In the ScriptableObject?
I dont think it will work to ref a child inside a prefab asset
But you can try it and see ™
well i changed the base movespeed for my tests, not my plyRunSpeed thats tied to the if statement for getkey
which is why im confused

Try it but you would need to automate the assignment and I expect it wont serialize properly
Sourcepawn is just a modified version of pawn. When you're using pawn from an application that is in c or c++ you can pass pointers to the objects to the runtime but you cant really get a pointer to a gameobject or component in unity so that isn't really possible in unity unfortunately 🙁
Yea pointers are not reliable in a managed language
just started unity (switched from making a game on roblox studio and want to make it in unity) and everything looks so daunting
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
follow some learning material!
cheers
float plyMvspd = plyWlkSpd;
if (Input.GetKeyDown(KeyCode.LeftShift))
{
plyMvspd = plyRunSpd;
isSprinting = true;
}
Each frame you assign the move speed to walk speed, then on the key that you press a button you change movespeed to run speed. So this code causes your player to only sprint on the single frame the key is pressed then it goes back to walkspeed
this is the game i was making before, and i want to make all of this and better in unity
Just generally struggling to figure out how to make it so that I can drop and pick up weapons, while automatically updating the weapons features
honestly i like unity's ui a little more than unreal, however there are some...other things about it that are questionable
still trying to learn the terrain editor for unity, but i think thats more because im bad at art.
Well you can reference a prefab asset on your scriptable object assets so why not do this?
UI like the inspector cause the actual UI tools are horrible
I like the ui system in unreal much better, its so annoying i have to write code to get a text label to display the value of a variable. I really wish we had some sort of databinding in the system.
the inspector and viewport, not the tools lmao
UI Toolkit is legit though
UGUI is not bad lol. You can do a ton without writing any code if you utilize the event system.
I also have to reference several child objects like the bulletSpawnTransform, muzzle flash, etc
UGUI is bad because it tries to be like flex but it fails at everything that flex does right
Your prefab asset should have some major component like "Weapon" and you would use this to manage the Instantiated instance.
You should only use the prefab reference to instantiate a copy.
but yippee, i have base movement set up, next up is jumping
its crazy to me you can set up ui with events to load scenes without writing a single line of code, but when it comes to assigning text from a variable you have to actually manually write it out
Yeah, it does, but my "PlayerWeapon" script, which controls the shooting, has references to the child objects to control when the muzzleflash appears (When shooting)
honestly if it werent for the fact unreal didnt save 2 of my projects in a row properly, i wouldnt have started learning unity instead
I mean i think figuring out what I was doing to cause this would be a higher priority than learning a whole new tech stack. but id be irritated atp too
Yea but you should handle this via your component ON the spawned object
e.g. Spawn gun from prefab, get gun component, do shit with gun component reference.
There is no sane reason to think about trying to reference a child of a prefab because its not in a scene, its an asset.
Question is there a way to add your own event triggers to the ui event system? or are stuck only with onselect onsubmit ondeselect etc?
one issue is that it said i was using the wrong engine version, despite only have one installed. Fixed that, happened again on the same project, so i fixed it again, and then it improperly saved my project and i couldnt even click it open
why? you can implement any logic you need with what is offered currently with UGUI
You can also try ui toolkit if you prefer that.
that was the second project, that made me swap
You cannot bind a variable to a text label but if I could implement my own event trigger I bet I could.
just made my first unity game that i coded myself. Should i release it on steam?
yea but you can code it yourself
You can make your own component to update some text using events for example. Why do you have this idea that it should be half magic?
this is more of a system than a game, i dont think releasing on steam is a good idea, since im also pretty sure steam charges 100$ to publish things on there?
but amazing job

because in unreal and godot you can do this without writing a single line of code. You just drag the object instance into the text component and then select which variable to bind it to. If the variable changes so does your ui
naahh im not releasing it on steam i was just kidding
see previous link
Does ui toolkit work with the ugui canvas?
its seperate but unity 6.3 added world space support for ui toolkit
im not on 6.3 unfortunately
also I dont like I have to learn some markup language to use it
Then if you want to use UGUI you can just make some components yourself to aid how you build your UI
well it wont happen so thats the end of that
The bones for it are already there
So back to my original question is there a way to create our own event triggers or are we stuck with the default ones?
whats is a trigger? A UnityEvent?
you can use then yourself if you want reflection based subscriptions
OnClick on Button is a UnityEvent thats invoked when its clicked

Im trying to create my own trigger for the event
Ah these are from event system and no you cannot make more
you are confused I think
These are called based on pointer interactions on a ui gameobject
You can respond to these via this component or yourself via interfaces but you cannot make more
unfortunate
so is it at all possible to write a custom data binder ?
yea ofcourse
You can write your own custom code to create a custom event that you can expose yourself . . .
You can use UnityEvent, SendMessage(), c# events, reflection... You can do many things yourself
I see. And is there a built in way to display a list of all functions and variables on a specific object in the inspector like they do in UnityEvent?
Yea you can get information about types via System.Type: https://learn.microsoft.com/en-us/dotnet/api/system.type.getmethods?view=net-9.0#system-type-getmethods(system-reflection-bindingflags)
Well yes I know about reflection but the inspector for unity event lets you assign an object and select a method from it. I was just wondering if there is some built in editor utility to handle the heavy lifting for me since they are already using this in the engine a lot
quick question, how are hitboxes made for players in games. Do you use the capsule collider (lets say a hitbox that determines whether a sword hitting you deals damage)
i want to know because im setting up jumping next.
Im not sure if i want to set up a floating capsule with a raycast that slightly raises its location, making it look like the player is on the ground when really its floating a little higher, or if there is an alternate item used for hitreg on players
i want to use the floating capsule, so that small surfaces sticking out of the terrain wont get the player stuck, and the player can just move over them
so is there a seperate tool for hitreg?
Like do I really gotta use reflection to set up my own inspector like this?
Yes that is how these fields and methods are retrieved to be displayed in these lists
Depends on the game. Counter strike hitboxes are a ton of seperate box colliders. I would avoid capsule collider approach. If you use capsule colliders things like animations will not effect the hitbox. So if you use the capsule approach you're going to have to adjust the size and position of the capsule if your player crouches for example. But with the way counterstrike does it each collider is assigned to the bone it represents so it just stays in the the correct place automatically.
interestingly new CS2 uses capsules
better for performance 😜
also it helps making the hitboxes more accurate
Same concept though tbh. Multiple small colliders instead of one large one.
is it? I always thought boxes were more performant
yes same I always assumed as much too
Never really gave it much thought though.
I thought the curvature creates complexities.. But I assume for accuracy capsules are a must
counterstrike has been just fine for 25 years using box colliders tbh
capsule is basically 2 sphere collider checks and then the distance inbetween
wondering:
can i assign enemy attacks to a certain layer
make my initial capsule that controls player movement ignore said layer
and then assign capsules based on the bone structure for the player to get hit by said enemy layer
not proficient with unity so idk if thats possible or not
yes and thats the way you should do it.
or at least reasonable
layermask is what you want
Does anyone know how to set a variable in Unity's visual machine if a condition is met (such as if the "this" object's Z position is x)
oh okay, i was more thinking about the curvature / amounts of sides that need to be calculated in the physics, but I don't much about this so I take your word on it lol
I don't know any good resources for visual machine
I would have always assumed a box collider performs better than a sphere collider too
Sphere is just "is the position within the radius" so it's faster
no because for a sphere all it needs to check is distance from the center
it's more complicated for a box
Capsule would be faster because it's just a position and a radius . . .
I mean either way isn't the box just a distance check as well? Either way its addition/subtraction on a 3d vector
The problem (not really a problem) with box collisions is when it is rotated. Those calculations cost more . . .
ah yes you're right
Honestly I am glad we dont live in a time where chosing box or sphere will make an actual impact.
i 🧡 choices
Sphere would be the fastest (even above a capsule) . . .
There are a lot of factors that goes into the equation of separating colliders. All of the primitive collider shapes are very fast though. I have always been told sphere is fastest and then capsule and box. Probably depends on way too many factors to give any proper comparison in general cases
True, as long as you choose the collider that best fits the object's shape, you're good . . .
You wouldn't be able to add to this because those options are pulled from the EventTriggerType enum. Your best option to create your own component with a custom drop-down of your custom events . . .
Ans is reflection really the only way to create my own drop down like this? Unity didn't expose a helper method for it since so many of their inspectors have the ability to do this?
What I am trying to do is be able to select a variable on a specific object in the inspector
Most likely. I've created my own drop-down but they're usually from an enum or manually written values. Since you're looking to grab variables and methods, you'll need to find public methods and/or variables from the type in order to display with, which involves reflection . . .
You should be able to find the editor file they used to see how they achieved it . . .
say I have gameobjects
- Root (Master Switch/Functionallity)
- Graphics (animation)
- Collider
right now I have a script called SwitchLink on the collider w/ reference to the MasterSwitch class on the root.. and I use a tryget for the raycast for the collider
is there a better more fundamental way of doing this?
i dont really like looping thru children or up to the parent.. (no clue why)
i got this round-about kinda way to access everything i need but just trying to minimize.. and now that i think about it this concept would apply to alot of my objects since they all have their own Collider object as a child..
so if i could realize some nifty way that im missing it'd be soo cool
I need developers
You use TryGet because it's not assigned and you want to make sure it is before accessing it?
using UnityEngine;
// SpawnCampGames
public class LabRaycaster : MonoBehaviour
{
public SwitchLink currentTarget; // link component on collider
private Camera cam;
void Start()
{
cam = Camera.main;
}
void Update()
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
// Check if the hit object has a SwitchLink
SwitchLink link;
if (hit.collider.TryGetComponent(out link))
{
currentTarget = link;
}
else
{
currentTarget = null;
}
}
else
{
// Hit nothing
currentTarget = null;
}
}
}
``` basically it'll be the only interactions i'll have in this demo... (just getting `SwitchLink`) via raycast
i just use trygets for the easy out lol
Not a channel for promotion . . .
i thought about doing Interfaces.. but they're really not needed since i only have (1) interactable
Where are Chanel for promotions
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
but whether its an interface or just a class doesn't really matter to me right now.. just wondering if there was a "trick of the trade" i might be missing
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
☝️ There you go . . .
i mean i could just put the collider on the root
but i thought i was being clever by having them their own object
if(Input.GetKeyDown(KeyCode.E)) currentTarget.switchMain.Toggle(); i guess this is clean enough
crying over spilt 🥛 i guess lol
This looks fine to me . . .
i'll take that.. and carry on 🙂
works fine.. i guess im just being dramatic
Also, I believe you can do:
if (hit.collider.TryGetComponent<SwitchLink>(out var link))
{
currentTarget = link;
}
else```
to remove `SwitchLink link;` . . .
ohh true... theres soo many different variations of TryGet i get confused
If you place the collider on a specific layer and use that layer mask, you can remove the entire TryGet because you'd know it has the component (if the collider is not null) . . .
how can i remove triangles from a mesh at runtime?
get mesh
get original data
rebuild it ignoring the ones u want to remove
apply new triangles list
Recalculate Mesh (normals/bounds/etc)
would i not get indexing issues
if you remove triangles that leave behind vertices.. you'll need to rebuild the vertices array as well
for (int i = 0; i < vertices.Length; i++)
{
if (updatedVertices[i].position.x == 21741000)
{
continue;
}
else
{
vertices[i] = updatedVertices[i].position;
}
}
mesh.vertices = vertices;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
meshFilter.mesh = mesh;
like this?
not sure.. i think if u remove triangles but keep the original vertices array untouched it shouldnt cause any issues
21741000 is what i put the x at when i want it to be deleted
because that causes indexing problems
Right now you’re “deleting” a vertex by shoving it way off at x = 21741000.. i thnk, im not 100 sure.. im just googling as i go..
but I think that doesn’t actually remove it — the vertex still exists in the array, and** if any triangle index points to it you'll error out**
i do that in a compute
after i have to rebuild the array of positions and then set it to the mesh
if it has the high x value i just skip it
ohhh
Instead of skipping those “deleted” verts, just keep their slots in the array and put them at some safe place (like (0,0,0)).
That way, indices still match up.
Triangles that reference them will collapse into degenerate (zero-area) faces → they won’t render, no explosions.``` does this sound like something useful?
no
ive tried that it just causes large stretched vertices
ive tried collapsing into neighbouring verts too and it causes the same issue
the only thing im seeing is something about Orphan Verts
if you dont delete or move verts but instead delete the triangles that use them you should have a "clean" mesh
but to be honest im outside my wheel house on this one.. just figured i'd try to brainstorm w/ ya since im here
In the OnEnable method i am trying to add a method to an event in my other class. but its null, i think the awake function not been called yet. any ideas on how to solve this, or a better way of doing it?
either change the order of execution or put subscribing in Start
its not guaranteed another objects Awake will run before this objects OnEnable
how do I add the drag event system to a unity class? Is it IPointerDrag? Where's the documentation for this stuff?
vertex[] updatedVertices = new vertex[vertexBuffer.count];
vertexBuffer.GetData(updatedVertices);
for (int i = 0; i < vertices.Length; i++)
{
vertices[i] = updatedVertices[i].position;
}
List<int> newTriangles = new List<int>();
int[] currentTiangles = mesh.triangles;
for (int i = 0; i < currentTiangles.Length; i += 3)
{
Vector3 v0 = vertices[currentTiangles[i]];
Vector3 v1 = vertices[currentTiangles[i + 1]];
Vector3 v2 = vertices[currentTiangles[i + 2]];
Vector3 center = (v0 + v1 + v2) / 3;
if (center.magnitude < 1000)
{
newTriangles.Add(currentTiangles[i]);
newTriangles.Add(currentTiangles[i + 1]);
newTriangles.Add(currentTiangles[i + 2]);
}
}
mesh.triangles = newTriangles.ToArray();
mesh.vertices = vertices;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
meshFilter.mesh = mesh;
fixed it
just remove the triangles and keep the vertices
no stringy vertices going 2171000 meters away 😍
there is IDragHandler, or you can use IpointerDown/Up set a bool to true and follow using Update or something
(for colliders these require Physics Raycaster on camera)
yup.. that was i trying to get out in my long winded ramblings 🤣
i also got it working
all about that Continue
skip those mofos
Thanks nav 👍 i was using OnEnable and OnDisable to subscribe and unsubscribe. do you know where i should unsubscribe if i am subscribing in start? or do i not need to worry about this?
what about IBeginDragHandler and IEndDragHandler? Are those outdated?
you can keep unSub inside OnDisable if you know you wont disable and enable again, or just OnDestroy if thats the case
i just realised i can create large destruction now really easily
you just need a ray triangle intersection function
no they are not outdated
they can also work. Point is you probably get a better result start/end drag to set a bool
IDragHandler always gave me weird result but could work
like seperating the pieces?
a lil AddExplosionForce at the origin?
this was my first time manipulating a mesh..
i didnt think of that
not too crazy (altho i testing w/ a cube) lol
you could create a seperate triangle mesh and add physics and push it out