#archived-code-general
1 messages · Page 367 of 1
When we talk about the length of a vector, it's best to think of it as a line originating from the zero point. It's implicit, we don't store that origin point in the vector, that's just where vectors start from.
Normalization is the process of getting a _unit length _ (aka length == 1) vector in the same direction as a given vector
Vectors have a direction and a magnitude. A normalized vector always has a magnitude aka length of 1.
That's all it is
It is useful because 1 times anything is that number
So you can get a vector in the desired direction of any length you want by multiplying the normalized vector by the desired length
Hello everyone, is there a script or utility for subtracting faces ?
(sorry I was in a tunnel so my answer was slow)
Maybe probuilder.
So I can just simplify it as just getting the direction and removing the length?
You can't "remove the length" direction vectors have to have a length, otherwise it's gonna be a dot in space.
Oh
What you can do is normalize it so that the length is equal to 1.
In a certain sense, yeah. Not removing the length but getting it in a very malleable form that we can work with easily.
Ah
please do not cross post
i apologize
also #🤯┃augmented-reality . Remove your previous posts and repost there
thank you
which version is more better? ( builder is stringBuilder )
builder
.Insert(startIndex, '<')
.Insert(startIndex + 1, styleTag)
.Insert(startIndex + 2, '>');
builder.Insert(startIndex, $"<{styleTag}>");```
Certainly the one with fewer Insert calls
Insert will likely be relatively slow compared to Add. It probably needs to shift all subsequent characters down in the array to make room.
also pretty sure the first example won't even work, since startIndex + 2 will not necessarily be correct if styleTag's length is greater than 1.
been searching for a while now but none to be found about faces subtraction
face subtraction meaning? if you are talking about deleting faces you can do that in probuilder
Amazing, one google search
not deleting.
wait i will make illustraction about it
I'm trying to reference things in a script variable through code, problem is the script is stored in a Component variable (It has to). Is there a way to convince a Component it is a Script?
as in trying to reference a script from another script
you mean something like this? public SCRIPT script;
a script is a component so explain
do you mean
Component c;
MyScript ms = (MyScript)c;
this is the variable. I'm trying to convince Component to let me use things like StopCoroutine
the script keeps changing to other scripts, its not just one
that is avaiable only for between GameObject and i believe it is not available to use during runtime
in that case use Monobehaviour rather than MyScript or just use Monobehaviour rather than Component
so what is this, not sure it gives any information
basically, upon a a main face subtracts a subface creates all the 8 new subfaces surrounds the subface
making the sum of the subfaces equal to original face
so you want on the deletion of a face you want to create 8 new faces around it?
what are you trying to do exactly here
not deleting a face, all faces must remain but the original face will be divided into different smaller faces
i recently implemented my own subdivision where the subdivision scripting for probuilder is not available
Monobehaviour did it, thanks.
is Monobehaviour another way of saying C# Script or is there more to it
Another illustration
it is saying ANY script which inherits from Monobehaviour
ah, you might be looking for an inset feature instead of subdivision
it is not available to use in a script right?
im not sure ive never messed with it
https://docs.unity3d.com/Packages/com.unity.probuilder@5.2/manual/Face_Inset.html
yeah not for scripting 😦
thanks @spare dome for assistance!
tthanks :DD
Hey all! Just wondering if it's possible to natively create a fading out or "soft" shape in Unity? This example was created in photoshop but it represents the general idea I am looking to get, in my actual usecase I am looking to create a halfcircle following the same concept. Thanks!
I dont think its clear what you're trying to do. Because this image somewhat looks like a texture for a shader. But the description suggests like soft body physics which is something pretty complex you'd have to implement
Nono, I mean "Soft" in 2D design lingo ahah. Just like the image, Like a shape that fades from a central point, like how a "2D Light" would fade from opaque to softer near the edges.
like just as a Texture2D or...?
just to get this out the way, why can't you cut the one you have there in half in photoshop? 😛
Yeah, or a sprite. I am using it for a "sunrise" effect in the background of my project, I'm trying to have it dynamically resize based on the resolution of the screen.
I can’t see why you don’t just create one in photoshop and export it. Are you using procedurals?
Haha, I am doing that now and I'm sure it'd probably work fine to just stretch it, but since the image is locked to a certain resolution, there could be stretching artifacts at wider resolutions.
maybe just make one big enough for the largest size you need to support? if it's a simple gradient it only needs one channel so it shouldn't be that big
Alright, I'll probably just continue doing that. I didn't know if maybe there was a way to just easily dynamically create something like that, natively I am using a 16:9 resolution however when "stretched" to fill a square resolution it looks quite out of place, was mostly just trying to mitigate that, but the amount of people using square resolutions nowadays are less than minimal haha.
it woudln't be difficult to create a texture dynamically for that but there's nothing built in, you would just need to create a texture and set the pixels youself
Alright, I'm sure I can figure something out to fix that programmatically either way, like a special vertical stretch percentage based on the width-height ratio or something. Not a super pressing issue at the moment or anything, but I appreciate the help all of you!
You can use procedurals
Just have an alpha gradient
the camera has an aspect property if that helps?
Hmm, I don't think I'm familiar with what that is?
Procedural shapes.
Yeah that could work, I am also just trying to figure out the canvas system in general so once I get all that figured out I'm sure it'll be an easy fix!
Haha I assumed that's what you meant but I haven't seen those before on here?
Oh, if it is a fixed aspect ratio svg format may be a good idea. IDK how well they translate into unity though
I can't seem to find any documentation natively either, is it a package?
if SVGs are supported that's pretty much exactly what I'm looking for!
supposedly they are compatible with UI Toolkit, so I'll have a look into that.
I’m not sure if it does or how well it does it
For procedurals? You can write them in shader code or go on the asset store and pickup “Shapes”
Ah, you mean using shaders. I'll probably look into that as-well I need to use them either way for a bunch of other blending in my background either way.
There used to be a package (in the package manager) that added support for SVG. Never used it, and don't know if it's still supported.. but go check that out
Oh thanks! I think the new UI Toolkit included with Unity supposedly supports them as-well.
hi!
im havin' problems with
a shader
it cuts itself off cause i enabled ZWrite to fix another problem
shader thing btw
#archived-shaders and you can also send everything as 1 message.
yeah sorry i just talk like that usually 😭
Can somebody explain why my script does this... Please I need help😭
can you show your camera setting
check if you have clear flags set to Solid Color
No way!
Thank you so much
I would have never thought it was because of the camera settings😅
can anyone help me figure out how i can detect if i'm hovering over a unity transform handle? i made a scene GUI listener for selecting objects in my custom world system, but i can't drag the transform handles because i have to call Event.Use() if the cursor is hovering on a world object, so clicking on the handles just selects my objects
this is the code for reference
hey everyone! im working on a top down space shooter type game with really floaty controls. i want to create a dash mechanic, but using rb.Addforce just doesnt feel responsive sometimes, any fixes?
seems more #↕️┃editor-extensions type problem
show !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
if(Input.GetKeyDown(KeyCode.W))
{
timeSinceLastW = Time.time - lastWTime;
if(timeSinceLastW <= doubleInputTime && canDash==true)
{
rb.AddForce(Vector2.up * dashSpeed * Time.deltaTime);
StartCoroutine(DashCooldown());
}
lastWTime = Time.time;
}
if (Input.GetKeyDown(KeyCode.S))
{
timeSinceLastS = Time.time - lastSTime;
if (timeSinceLastS <= doubleInputTime && canDash == true)
{
rb.AddForce(Vector2.down * dashSpeed * Time.deltaTime);
StartCoroutine(DashCooldown());
}
lastSTime = Time.time;
}
if (Input.GetKeyDown(KeyCode.A))
{
timeSinceLastA = Time.time - lastATime;
if (timeSinceLastA <= doubleInputTime && canDash == true)
{
rb.AddForce(Vector2.left * dashSpeed * Time.deltaTime);
StartCoroutine(DashCooldown());
}
lastATime = Time.time;
}
if (Input.GetKeyDown(KeyCode.D))
{
timeSinceLastD = Time.time - lastDTime;
if (timeSinceLastD <= doubleInputTime && canDash == true)
{
rb.AddForce(Vector2.right * dashSpeed * Time.deltaTime);
StartCoroutine(DashCooldown());
}
lastDTime = Time.time;
}``` This is all in the update function
here is the coroutine
IEnumerator DashCooldown()
{
canDash = false;
yield return new WaitForSeconds(dashCooldown);
canDash = true;
}
well first i would put addforce in fixedupdate and i would also use a movedirection so you dont have to look at all of this,
to start with you should wrap all of that code in If (candash) so you don't need to check it at every stage
okay i can do both of that, it was pretty late when i wrote that so i must have been zoned out or something hehe
a movedirection?
dont use Time.deltaTime on addforce, thats why its messedup too. Also would go with Impulse mode instead if you need one frame
yes
Also, look at the AddForce documentation and see what different ForceModes you have
so you only apply a force once
instead of several times
its pretty common
Movedirection = orientation.up * Y + orientation.right * X and you use this to apply a force
X and Y are inputs
via getaxisraw
ahh i see, what are orientation.up and right?, are they 0 and 1 values?
no they are the direction(s) of your player
just change orientation to Player
or whatever transform you have
okay, but thats only for the efficiency of the code right? this wouldnt change how the dash would work. i removed the Time.deltaTime multiplications and put this code into FixedUpdate and now the dash is even more inconsistent :/
yes it is for the efficiency for the code, but you have to put the inputs in Update() and the physics calculations in FixedUpdate() since that is on the physics update
if you put the inputs in FixedUpdate() it will act a little wierd
hmm, so i how would i call the rb.Addforce in FixedUpdate() from the if statement in update()?
maybe i could do that using booleans?
well if you use the Movedirection you can just do RB.addforce(MoveDirection * Speed, Forcemode.Force)
and thats it
pretty much
alright, so i use GetKeyDown for the double input checking, then i use GetAxisRaw to check which direction im going, and apply the force in that direction?
and MoveDirection is a vector2 value?
no you do not need to use GetKeyDown for anything all you need to do is set up X and Y like
x = Input.GetAxisRaw("Horizontal");
X and Y are inputs and produce a 1, 0 or -1
what about it?
is my timer not working around GetKeyDown for the second input within the timeframe?
you can just put the timer around the movedirection if you want
i havent use double tapping inputs in a while
i think using getkeydown wouldnt hurt no
you could probably just do
if (X)
{
timeSinceLastD = Time.time - lastDTime;
if (timeSinceLastD <= doubleInputTime && canDash == true)
{
Timer = true;
StartCoroutine(DashCooldown());
}
else
{
Timer = false;
}
lastDTime = Time.time;
}
something like this
you would have to mess around with it
hmmm yeah thats pretty much it but condensed
unrelated question, but is there like a trigger system for just code, like there is in animations?
I'm trying to make a procedural passive skill tree for my game and am running into some issues with constructing a possible tree with no overlaps (currently just having them connected in 4 directions (up down left right). I'm currently doing this iteratively but its a not working so well especially when there are "branching" nodes that have more than one connection. I feel like this could be solved much easier with backtracking/recursion but i'm not exactly sure how to do it. Any sugessions?
i mean theres an enum
if thats what you are looking for
hmm, maybe just switching to your movedirection method would be easier
how would that look like? if you dont mind can you sort of write a bit of it
i dont wanna just copy paste im genuinely interested
well i showed you how from here
so what i understand from this is that "orientation" is a vector2, and movedirection would give me a float, which i could just input into an rb.Addforce() method? i'd have to change my movement script for that right. thats in another script
nevermind that wasnt too hard
orientation is the orientation of your player (transform of your player), so you can change that to fit your code. movedirection is a vector3
and i showed you how to implement it into addforce()
oh like its rotation?
is orientation a variable name or a built in function?
yes im getting that
orientation is a transform which is a variable
all it is, is a transform of your player
alright, thank you!
cool beans
fun fact, but AddRelativeForce exists so you don't need to use the transform to multiply the individual axes to get the world space direction of force. just pass the local space direction to AddRelativeForce and it does the work for you
man im still stuck, i cant figure out how to check for double inputs using GetAxisRaw
What does "double inputs" mean
didnt i help you with this?
like double taps
that should do the trick
man im forgetful
but like then even if i press A then i press S, it would dash down
that doesnt ensure the same button is being pressed
i updated it
that should do it
all getaxisraw is, is an input
it acts like W A S D
hey guys i wanted to make my player a prefab(for clclasses) but now i dont know how i make my inventory work bc i cant asign anything does any1 know something? https://hastebin.com/share/ejetodofaf.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
but getaxisraw checks for inputs every frame no?
sounds like u are trying to assign scene objects to a serialized field on a prefab. you cannot do this
the solution depends which things here you're actually trying to assign. it could just be a matter of telling this inventory script what the references should be when you instantiate it, or making other objects prefabs too.
just like normal inputs do
if you look at the code its basicly every public variable
no but its continous, if i keep holding it its going to consider that too
unlike getkeydown
and i am sorry i am a beginner what do you mean with instantiate it and making it prefabs
you can do a waspressed check if you need a getkeydown type thing
i might have to dig to find mine
it should be pretty simple fix I just need to make MoveRotation move slower or maybe use some other rigidbody method I tried AddTorque but it doesn't work cus it needs Vector
This should definitely be in #💻┃code-beginner then. But regardless if you have a prefab you need to instantiate it so it exists in the scene. Look up the method Instantiate and try it out.
Prefabs can reference other prefabs, so some of those objects you're trying to reference might be fine to turn into prefabs as well. Otherwise youd need to assign the value in a different way, like at runtime.
it has to be a simple fix but idk
I reinstalled Unity on a new computer recently, and everything seems to be working fine except I have to regenerate project files every time I create a new script file or Visual Studio bugs out.
Specifically, the new file I created will be present in the solution explorer but won't be able to find any dll files including System or Unity itself.
Is there a checkbox I forgot to press or something? Or is this an issue someone else has had too? I'm on LTS 2022.3.43f1 using Visual Studio Community 2022
(Regenerate project files resolves my issue, but only temporarily as I will have to do it again once I create a new file)
Is your visual studio package in Unity up to date?
Well, there is no "Update" button available in the package manager, the version says it was released October 11th 2023 though
My install is like, one week old
The visual studio package is on version 2.0.22
Specifically, adding any code file at all causes this to all my references in the whole project:
Hey, what's generally regarded as the best solution for getting a class from a collision target?
'Cause I can think of 3 ways, two of them seem like bad practice.
-
Use tags. Just probably a bad solution overall considering how clunky tags are.
-
Use
TryGetComponent<>(). From what I understand this is horrible when it comes to performance. -
Write a manager class that objects of a class register to
OnEnable, then handle the collision checks in there. This seems like the most logical solution, but I feel like writing something that would be performant would be difficult, and wasteful, as Unity built the entire 2d collision system for this exact reason.
Just use getcomponent
well, not to check what kind of object it is maybe. If you want to test the object for type then tags seem to be the accepted solution
You can't have multiple types of tags on an object though, can you? And it's very prone to typos
TryGetComponent is completely fine
Nothing wrong with it from a performance perspective
That's the best solution IMO
Yeah like it's not the absolute cheapest function in the world but
it's very unlikely that will be the thing that slows you down
unless you're having thousands of these all the time
I'd dare you to even find the impact of TryGetComponent in the profiler. It's fast.
This also gets you directly to the data you will need, rather than requiring a subsequent call
If I'm making a Projectile class for example, and an enemy that shoots 10 bullets at a time, having each of them ( x however many enemies you have on screen) run TryGetComponent() every frame seems... suboptimal?
It's fine
Try it and see
the 10 bullets aren't colliding with every enemy on screen every frame
If you're really dealing with thousands of objects on screen at once you should probably be looking into ECS anyway.
...huh fair enough. I was really convinced it's a bad solution 😅
Touhou levels of bullets should be fine though
This is so annoying though. Every time I add a file my csproj takes a dump and I have to break flow to restart visualstudio
Thanks you two!
Why would you need to do that?
Running TryGetComponent that is
To make entities take damage.
Currently just have a Damageable class that holds HP and an event OnHit
Personally, I would handle dependencies another way than GetComponent
More of a organization thing than a performance thing
Though if you are making a touhou clone 100% manage dependencies some other way lol
It's unclear exactly what alternative you're proposing
The physics engine is faster than almost anything you would write.
When did I mention the physics engine?
We're talking about Raycasts
Which give us colliders
And the way to go from a collider to data associated with the Collider (I e. Another component) is to use GetComponent
Outside of that you'd be talking about your own home grown physics queries or something, or some other way to associate data with GameObjects... a dictionary? Which doesn't seem like it'd be any faster or easier
I don't really use them much, but I assume Unity tag comparison could be quicker, but I guess you still need a component look up anyway?
Also, I've not looked much into it, but does the component search linearly or is it all hashed
I've never been convinced by CompareTag being somehow faster than TryGetComponent. Doesn't CompareTag have to iterate over the whole tag to check for equality between the tags?
Is that really faster than comparing the class type pointers? And iterating over a similar or smaller number of things
HashCode() for a string iterates the whole string afaik, unless it's cached.
Honestly, it's all probably a micro-optimization anyway, and doing GetComponents each frame (even multiples) is pretty common
Indeed
I thought this was regarding dependencies via trygetcomponent. What was the issue with raycasts?
We're starting from a Raycast
Is there some rule against installing Unity on the D drive or something
Now you need to get the data about the thing you hit
And you're suggesting against using GetComponent
like, does the main unity install only work on C?
Pretty sure you could code it so that you completely avoid this
So I'm trying to figure out your alternative
No. But you’re cache will be on C#
my cache?
Yes
I'm not sure what cache you're referring to
Like your lightmap baking and stuff
oh, sure
I'm being told visual studio can't find any of my references, but when I look in the project file and check the path the references lead to, I find the dll
Reinstalling Visual Studio, deleting the library folder, etc doesn't fix it.
That seems like a vs issue
Closing and re-opening visual studio fixes it until I do something else that disturbs the fickle VS gods
Well, it triggers when unity does the reload domain or whatever thing it does when you move or add files
i was getting this issue recently
managed to fix it in the end
second let me check how i did it
clear your project in preferences, like you normally do and i deleted the relevant folders so it will properly regenerate, then i closed unity and re-opened. Then instead of double click scripts to open VS i instead linked it via assets > open c# project
that seemed to properly link vs to unity
after that i could once again double click open links
im also making sure unity is on latest version of unity 6 and vs is also updated
Hm, what did you delete to make the project file regenerate?
library i think
not sure but i didnt delete that
I've deleted the library, regenerating only temporarily fixes the issue as it immediately happens again when I make a new file
using the assets - open c# project did not help
I can double click to open files though, my issue is just that the csproject loses the references
It's almost like the project file itself ceases to exist
Like, the project file was deleted and replaced with a new one, but visual studio still remembers the old file which it can no longer read
This appears to be the case, actually. Really strange
Huh. Adding the "player project" to the list of projects to generate fixed it. If anyone else has similar issues try that
I don't know what that project does, but as long as it doesn't break my flow I'm happy
Hey guys, so i have this class which spawns another class setting a variable in it called "radius", also in this class if it collides with a certain object, it creates an instance of itself without setting the variable "radius". problem is, the variable "radius" is set to whatever it is set in the original class that spawns it. i will share screenshots, hopefully it is clear.
1st screenshot is in spawner class.
2nd screenshot is in the ripple class.
-notice that .Setup() is called only from the spawner class, and not ripple class. but radius is set to spawner class on all ripples regardless.
radius in spawner class is set to 5, in ripple class is set to 1
i mean in the prefabs
but all ripples get spawned with radius of 5, the spawner, regardless.
and i dont know why is that
I'm assuming the referenced prefab from the ripple class isn't the prefab but a reference to itself - cloning.
The clones would then have the same data as the cloned object.
well i just select the prefab, and put itself in the refrence
so i guess thats why?
A workaround (without having to change too much of your current setup) would be to cache the spawned instance and set it's prefab to the asset prefabcs var ripple = Instantiate(rippplePrefab, ... ripple.ripplePrefab = rippplePrefab;Referencing from the inspector would reference itself, unfortunately - useful in itself but not for your case.
I see, thanks
Hello! So quick thing, im having issues and IDK if the issue its on my health system or bullet system, my guess is on the bullet system since I tried to get a hit confirmation on the debug logger but im unable to make it work, so first pic is going to be the health sys and the second the bullet one if anyone can help me with any insight (I really dont understand c#)
well what errors are you getting
im guessing you are getting some
So the health system is working as intended but the bullets bounce on the dummy and dont remove from his pool of health
The console doesnt give any errors
I tried using the debug.log to get to see if the bullet was working but it haves no effect I can share screen if you wanna see
why are you not doing collision.transform.gameobject.getcomponent<Health>();?
Im sorry I dont know where would I place that, Im not knowlageble in coding that much and im basing most of my code from puting parts from tutorial to tutorial and making them work together
you would put that where healthcomponent has its getcomponent, keep in mind C# is case sensitive
so you must write the code with the correct capitilization
Like this?
yes
i would suggest !learning unity to fix this next time
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Why tho? It wasnt collecting the health component from the collision object?
you were trying to get a health script from nothing
but you need to get the health script from collision
you could use a try catch next time to debug if needed
Ohhhh, I was guessing it would be either that or that the bullet wasnt reallly colliding with anything
Try catch?
try{
var healthcomponent = getcomponent<health>():
}
catch{
//make a debug or error
}
it will try something, if it cannot do such thing it will throw an error
Thanks! This actually helps me a lot, Im trying to make sense of a lot of this, but it all looks like rune language to me so im trying the best I can, thank you @spare dome
i would suggest !learning unity, you will get a lot better over time
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
come back any time for help!
so just need some help regarding conceptualizing what im thinking of, im working on a card game atm and trying to create a pseudo-statemachine? i dont think im 100% following the pattern to make it work with my situation but wondering if theres a better way i can handle this
the state machine itself has some state transitions, but from what i understand you dont usually inject states with data?
for example, lets say im in some state and i want to do a "draw card action", i dont necessarily need to do a state transition to draw a card, but i want to update the current state and its relevant information with the additional cards
am i conceptualizing this wrong?
what are these states
specifically:
- start game/init
- draw mana
- draw card from deck
- player turn
then during the player turn, they decide they want to draw a card lets say, it doesnt really make sense to make it a state here right?
because theyd draw the card but it would still be the player's turn
unless you think maybe i should make it something like a state where its only function is to draw a card, then it immediately transitions back to the previous state?
I'd handle it with a sequence of logic like methods such as:
BeforeDrawPhase()
AfterDrawPhase()
BeforeCombatPhase()
AfterCombatPhase()
oh sorry, i meant the draw happens after player turn
so it would look more like:
- player turn
- they decide to draw a card as an action
- still the same players turn
Good example of a state would be clicking a card and figuring out if the player can play it or not when invoking IPointerHandler
If(Player.state == Phase.CombatPhase):
//play card
also for some extra info, my state machine has the normal Enter/Exit methods, but it also has an additional method called "TryGameStateAction" which passes some eventargs, and in some cases it might queue the next state, modify the current state, etc
ignore the boolean, but example here
Games like Yugioh it's probably a bit more complex with states, but something like SlayTheSpire is very linear in how state logic works
definitely a bit closer to yugioh than slay the spire
based on cards certain actions might be possible or not for example, card effects can be activated, etc
Still, I think states would be indentical to how phases work in yugioh.
You got the draw phase, the battle phase, the after battle phase
true
I'd imagine it's a total mess for how those games are coded.
there's just so much extra stuff to keep track of for when you have some complicated effect in place
yup lol, there actually is a unity game of the card game im trying to make right now and i decompiled the code to take a look, total mess lol
game logic script had like 15k lines of code
seeing if i can create it without making a total mess
I'd structure it more and make a rule set for the ordering of effects
pretty much what im looking to do
i guess my difficulty is lying in the fact that some actions dont cause the game state to transition but some game state data to still update?
but i guess even the action of "drawing a card" can be a state in its own then i immediately transition back to the battle phase
drawing a card would be similar to my method above:
BeforePlayerTurnPhase()
{
//Draw Card
}
yeah but its a player action, so the player has the choice to draw or not
Ok so that would be during the phase then
exactly
If that doesn't advance the phase, you just flip a bool or create another substate of sequences
wdym by create another substate of sequences?
Probably give me more of an idea what would happen if a player draws or not
we are in the player action phase => some game state data gets updated so that the player has an extra card in hand => still their turn
we are in the player action phase => player doesnt draw => still their turn
if they draw or dont draw the resulting state is still the same
Right, so you're just awaiting for the player to confirm, but ultimately nothing in the state changes (that would otherwise cause split logic)
so IPointerHandler callback or w/e input method will be what advances it
as for something like substates, you can do another handful of states/enum for each specific phase
for the state machine pattern btw, there usually isnt persistent data between states right?
PlayerStatePhase has substates of DrawingCard, BeforeDrawEnd, ect
well, usually you do have flags that would persist.
yeah that makes sense
Not everything needs to be a state as sometimes you just need some bool to compare against in other phases
makes sense
hmm alright, i think i have a decent idea of what to try now too? makes things a bit complex since actions can be optional but i think i can manage something?
I've only made like SlayTheSpire type games where all the logic is very linear but I've probably got some ideas
its not a very linear game unfortunately lol so im definitely not able to stick to the design pattern 100% but im modifying it where it matters hopefully
I'd totally keep TRAPS and stuff like that very generalized. Don't have 10 types which can be activated in specific phases
spells can only be played in like battle phase, ect
oh unfortunately there are some cards that can be activated in different phases lol
example, theres cards that can be played during your turn or during the "counter" phase
but i think i have a solution for that at least
Right, I'm saying that try to keep a generalized amount of requirements. WhenEnemyMonsterIsPlayed, WhenPlayerTurnEnds, WhenEnemyMonsterDies
ahh, yeah of course
no yugioh BS like if monster is 1000 hp and you have half life total and there's a solar eclipse
i wont be making one off methods and things like that
very much will be generalizing requirements, plan on making some editor scripts to make those things easier for card effects and all
Is there a limit to how many items I can initialize in a list through the inspector
I'll likely max out at like 200
So if that's not an issue then I'm squared away
There's probably no limit(aside from the maximum list capacity). Though it might get laggy the more you add.
As long as it doesn't affect in-game!
i'm at a loss
With division perhaps you'd want to use floating point values?
4f/5f
that is how int division works. 4/5 is 0, the values are truncated meaning the decimal is dropped.
4/5 = 0
0 * anything = 0
by using floats you keep the decimal
i always assumed it knew when to switch to float, but I guess ill have to use 'f'. Thanks!
Hello, does anyone know why the Unity DevOps isn't working, I set everything up correctly, but the other person can't add the UVCS repository in the unity hub
Hello, wondering if someone could help me with what should probably be a very simple fix - In the following code when a TransformPoint moves the newRPos isn't updated and the offset applied is wrong in MoveInitialRoundingPoints()
I can see that the amount it's incorrectly offset by is equal to the distance travelled when the TransformPoint is moved, so I need to be able to update newRPos when the TransformPoint moves, but this causes unexpected behaviour because I think it's being updated whilst it is moving.
Any suggestions?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
This is a lot of code. Any chance you could isolate the part that's not working properly?
Or at least point it out
It's also not clear what you mean by TransformPoint moving
Here are the 3 isolated methods, I'm shooting a Ray at the Points, if it hits, the point moves with the cursor, the movement is clamped between two values, their InitialPosition upon instantiation +||- 0.45f
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You are going to have to step through the code with the debugger. The paths through the code and the values used are too dependant upon the values of variables like index, which we cannot know
yep that's no worries, I know exactly what's happening and how much the offset is incorrectly by, and even where it's happening so it shouldn't bee too difficult to figure out
does some1 know how to make a inventory if your player is a prefab?
like ways to do it with the asigning adn stuff
Many different ways. And the fact that the player is a prefab is probably not very related to it.
what are some of the ways?
The simplest form is an array of items or ids of the items.
well its not for the items but for the inv it self
Wdym by "not for"?
this is how you can implement an inventory
If that's not what you're asking, then clarify the question
wait ill grab my a good idea for you
public List<Slot> inventorySlots = new List<Slot>(); i have this in my normal inventory but when my player is a prefab i cant asign the slots same for something like this public Transform dropLocation;
Yes, that a bit more complex implementation than I suggested.
- You can assign the slots at editing time in the inspector.
- You can assign them at runtime via code.
i think the second is more simple so i think just making an empty object with a seprate script that asigns the slots?
and if i understand number 1 corect than this woukd be imposible when an actual person is playing the downloaded game
Why do you need a separate object for that.
What? No. The data would be included in the build.
bc you cant asign them in the player right?
- Yes you can. I explained how.
- You don't need a separate object to do it via code. The logic of adding slots or items should probably be a part of the inventory implementation.
- with the findtag?
No
Maybe expain what you're trying to do first
Are you trying to populate the inventory with the initial items? Or give the items on certain events in the game?
what i am trying is that when the player spawns in he has the inventory
but i cant asign the slots
Then assigning it in the prefab should be enough
you get a type mismatch
If it doesn't work as you expect, you'll need to clarify
so you cant
Then you're doing something wrong
do you have unity open?
You'll need to clarify and provide details
No
but if you ahve a item in the scene and you have a prefab you cant asign the item in the scene to the prefab
That you definitely can't. Why are your items in the scene?
Items should just be data. An SO or even just a plain C# class/struct. They ui icons, or whatever you're referring to, would need to be updated at runtime with the data from the player inventory.
You're doing something very wrong if your actual item data and logic are part of the canvas
You can assign prefabs/SOs/other assets or even define the item data right in the prefab.
The only thing you can't do is reference objects in the scene
What type is InventorySlots?
Both. There's no difference between the type in code and in the inspector
Why is it an image? Are your items just images?
Besides, an Image is a ui component. It's not even a texture/sprite.
i am not trying to asign the items just the inventory it self
Ok, I think I get it. All this time you were asking about inventory ui and not an inventory system. Is that correct?
And how to bind it to the character actual inventory
yep
Ok, you should make your intention clear from the very start.
But anyways, you can bind your character inventory to the ui when the character is instantiated.
Then your ui would need to iterate the character items and generate icons for them in the correct ui slots.
inventoryUIManager.Bind(character.Inventory)
thanks i will try this
Just in case: that line alone wouldn't work. You need to implement it.
okey
Guys, please tell me how to create an inventory. I don't understand anything from these tutorials on YouTube; they all use the same template. But I want to understand how to create an inventory where there are objects of different types with various parameters, even if they are the same object. How do you display this on the view and how do you save everything, including both the order on the view and the objects themselves?

What view are you talking about?
As for the inventory, the simplest form would be an array of items. Might want to have a look at the previous conversation as it was about inventories as well.
Is there a way to have onvalue changed in the inspector for toggle to accept parameters other than bool?
I want to set which gameObject will activate when a toggle is On from the inspector, or is that not possible?
public void OpenTabContent(GameObject content)
{
previousContent?.SetActive(false);
previousContent = content;
content.SetActive(true);
}
Can you tell me how to start building an inventory system correctly to support a large number of items? Let's say the first class should be 'Item'. What should I do next, and what should be in the 'Item' class? Let's take the game '7 Days to Die' as an example
@trim thistle can i msg you i have a good tut
Well, it would depend heavily on how you want it to work. But I don't think. A list/array of items can store more than a large number of items, so that shouldn't be a concern.
Item class can be many things depending on how you plan to use it. It could contain the item data, or it could be a runtime instance that references the data and identifies an physical item in the game world.
So the contents of the Item class would depend heavily on what intention you have for it.
How to have objects of various types and different parameters? Well, you’d have all of the items either derive from an abstract class or interface that allows them to be stored and accessed in the inventory. They’ll have to be stored in a collection, likely a list but if you have specific slots a matrix may be better.
How to display the items? Iterate through each inventory item at get the information about the display before adding it to the screen. This step largely is based on your framework, but for Ui you can instantiate items into a layout group and set their texture to the item’s texture.
How do you save everything? This really largely depends on the dats structure of the items. You would probably use binary or json serialization to write a file. Just note that the default unity serializer is a bit limited
https://www.youtube.com/watch?v=5l2D6xtZIgk this is a good 1 and a good series
Support the Channel!
https://www.buymeacoffee.com/HawkesByte
Hello to all new and old, I'd be surprised to see if anyone still remembers this channel but I'm back with something a little different! A common question I would get when I was still developing my survival game was how the inventory system worked and if I could make a tutorial, and ...
inventories are fun
Sorry this isn't the right channel haha, I'll move it sorry!
(But also, you have to make your shader transparent)
Oh, I see! Do you happen to know how I might go about that? (Figured it out, Thanks so much!)
Had to connect my "Sample Texture 2D" to the new alpha channel created, appreciate the help!
So I’m trying to use a flood fill algorithm on a texture generated during runtime to add color variation and what not I have the basic set up I want but simply don’t like the way it looks it generates circular is there a way to add ig noise to it or random variables so it can spread in different directions
Maybe show us examples and your code?
Hey so I don’t have time to show the code or open unity because I’m at work. But what is the best way to understand code you want to reapply in your own project
read it line by line, and learn what its doing, how its doing it, and why
Yeah. Dont proceed until you understand
I mean I kinda understand but how do you start by making it in your own project. I doubt copy and paste is a good idea
if you know how it works and why it works and know how your project works should be able to adapt
Like anything, try to reproduce without looking.
Hello i am having code existential crisis where my test run works perfect but upon testing on a mesh model it buggs out
https://gist.github.com/RagnarokFate/8df399d61398a27f63493d7d9f30ead8
Test Code where faces are manually made
and ... cube face subtraction :
AHHHHHHHHHH
the goal is to 'subdivide' faces based on a given subface and create the 9 subfaces that combined together makes the main face (no overlapping)
Build up your test into your actual test.
Maybe you have issue if vertices are shared
Or maybe you have issue depending on your object bounds/space.
sry but i don't get your intention
You have a square which is not a cube.
i don't affiliate myself with sharedvertex or other properities in probuilder.
what i do in my project (cube) is obtaining the closet face i'm clicking on and preview shows subface being made. the main face (top face of cube) has been chosen without mistakes nor creating a subface. But, idk for some reasons it is not working as it should be.
You clearly shown a mesh that is being cut. If it was working in a test example such as having (A single face), it is mostly not working because a cube is not the same as a single face.
import a cube from a dcc package that way you can ensure it is made correctly for your purposes and rule out how hte mesh is made
since you can ensure there are no shared vertices
You can have share vertices, and the position of the vertices will not be the same (same if you take a single face) the your test case.
Programmation is not magic. (At least, in your case)
but i'm doing my concept on faces level of the cube not on all cube faces.
// Get the final rectangle vertices
Vector3[] rectangleVertices = new Vector3[4];
for (int i = 0; i < 4; i++)
{
rectangleVertices[i] = lineRenderer.GetPosition(i);
rectangleVertices[i].y = 1.0f; // Ensure the rectangle is on the same plane as the mesh
}
// Add vertices to the mesh
List<Vector3> vertices = pbMesh.positions.ToList();
List<Face> faces = pbMesh.faces.ToList();
int[] vertexIndices = new int[] { 0, 1, 2, 2, 3, 0 };
for (int i = 0;i < vertexIndices.Length; i++)
{
vertexIndices[i] += vertices.Count; //offset the indices
}
Face newFace = new Face(vertexIndices);
vertices.AddRange(sortedVertices);
faces.Add(newFace);
pbMesh.positions = vertices;
pbMesh.faces = faces;
//subtract the face creating 9 new faces and remove the main face aftwards
FaceSubtraction faceSubtraction = new FaceSubtraction(vertices, faces);
faceSubtraction.SubtractFace(pbMesh, closestFace, newFace);
Yeah, and I'm saying that the position of every face in the mesh is not the same.
And as I said, those are only possible factors. It does not mean that in your case it is an issue.
I'm just pointing out that by building your test case of a single plane (that from what I understood was working) towards a Cube, you are mostly going to find the issue.
When there's two scenes active, how do I control the UGUI draw order of elements in different scenes?
I have a UI element (in one scene) that's appearing above another element (in the other scene).
The scenes don't matter much. What matters are the canvases
they each have a canvas.. is there a canvas draw order?
Which render mode are the canvases using?
screen space - overlay
Yes - sorting layer and order in layer
Or is it greyed out for Overlay? If it's greyed out then it's just hierarchy order
I have these two canvases, one's got a sort order of 1, the other a sort order of 5.. but an element in 1 is somehow appearing over elements in 5
not really - everything within the canvas is part of that canvas. You can order things within a canvas based on hierarchy order
ooooooooh one canvas is overlay, one is screen.. hm
Yeah in that case the overlay one will always be on top IIRC
overlay draws after all cameras
hm.. ok, that seems to make sense.. this is gonna be a tricky bug to figure out
Given a face of a mesh, is there a method to distinguish if the current face is clockwise or anti-clockwise?
All faces in Unity are clockwise
Unity actually only uses triangles
and all triangles are clockwise
Hey! Is there a way to move the mouse with a joystick while using the Unity Old Input System?
I know there's WarpPosition but i'm not sure how to work that while using the old input
Nope. Not supported in the old system. Best you can do is use a GameObject as a virtual cursor
Dang, that stinks. virtual cursor seems like a bunch more work too.
I do like the new system and am decently familiar with it, but sadly for the purposes of this project it wouldn't be reasonable to switch.
I'm in too deep lol
¯_(ツ)_/¯
You have to weigh that cost vs the cost of implementing something with the old system
Oh well, thanks for the heads-up anyway!
There's always the "both" option
You mean both new and old input systems?
Yes.
Oof, seems like it would be a headache. Wouldn't it cause incompatibility when old input code is trying to run even though its obsolete?
What kind of incompatibility?
The main cost is performance - you'll be running both systems.
And the fact that half your code will use one and some will use the other.
i mean a ton of people have the old input system implemented still
so they kinda have to
I prolly will still just stick with old for now unless I get super desparate lol, I appreciate the advice tho
Hey guys, I am taking the leap to trying to code my first multiplayer game and am coming across some challenges I cant find solutions to (or solutions that seem like spaghetti)
Here is the scenario, I have a host and a client that can connect to each other and everything is working great. I want to spawn an enemy for both players, typically in a single player game I have only 1 prefab for enemies and 1 scriptable object to define traits for the enemy and map them to the prefab when the enemy is spawned. However, for networking this it seems more complicated but I have figured out to be the basics, I still have 1 enemy prefab and 1 scriptable object and have figured out how to map all the network variables from the SO to the prefab except for the sprite since there is no network variable for sprites.. So currently I can spawn an enemy for all clients and the 3 network variables i have defined are being shared properly, I just need to figure out how to get the sprites to propagate to the clients.. here is some of the code
I tried adding this to the spawn enemies function with it only working on the host and the clients not seeing the change.
enemy.GetComponent<Enemy>().ConfigureEntity(enemy.GetComponent<Enemy>().entitySO.sprite);
I thought about trying to use a client rpc to propagate the change for the sprite however any client connecting after the rpc would not see the sprite.
Any insight would be much appreciated.
I would probably use a NetworkVariable with either an int, an enum, or a string, and use that to identify which sprite I want - or better yet use it to identify which EntitySO I want
basically - give each entity an ID
and come up with a lightweight system for looking them up by that ID
so the client can do so based on a simple identifier
Ok, so are you suggesting to store all of my enemySO in some sort of data container then pass the id of the specific enemySO in that data container to the clients and have them update the prefab information themselves? If this is the case, the server would configure all of the network variables that are housed in the enemySO and the client would only need to update non network variable information themselves?
are you suggesting to store all of my enemySO in some sort of data container
Yeah sure, like aDictionary<string, EntitySO>so you can look them up.
then pass the id of the specific enemySO in that data container to the clients and have them update the prefab information themselves
Yes. they would look up the SO and use the data inside to update the sprite on their end, for example.
Ok Ill give this a try, thanks for the info!
Hi guys! I have been working on integrating an Unity XR app into react native based IOS app and it works but when I close unity using unloadApplication and then put app in background, it crashes with the following stack trace, happens on iPAD (works fine on iPhone)
Hi! im trying to render my shader (which i made with shader graph) to a texture. this is my current implementation, and im my head makes sense, added comments to help show my process
public RenderTexture rt;
public Shader shader;
Material mat;
MeshRenderer mr;
// Start is called before the first frame update
void Start()
{
mr = GetComponent<MeshRenderer>();
mat = new Material(shader);
mr.material = mat;
mat.SetTexture("_MainTex", rt);
mat.SetFloat("_stps", 6.3f);
}
void savePic()
{
// create rt and tex
RenderTexture finalRenderTexture = new RenderTexture(rt.width, rt.height, 0);
Texture2D tex = new Texture2D(rt.height, rt.width, TextureFormat.ARGB32, false);
// take the base render texture that has what we see, then apply that to the finalRenderTexture with the shader materia
Graphics.Blit(rt, finalRenderTexture, mat);
RenderTexture.active = finalRenderTexture;
// read in whats in the renderTexture and save that to tex
tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
tex.Apply();
// save tex as a png
byte[] bytes = tex.EncodeToPNG();
File.WriteAllBytes(Application.dataPath + Convert.ToString(DateTimeOffset.UtcNow.ToUnixTimeSeconds()) + ".png", bytes);
RenderTexture.active = null;
finalRenderTexture.Release();
}
the problem im getting is that it saves the texture out as a black images so i assume something is not been set right somewhere.
Thanks!
note i've removed the update method where i am calling savePic, character limit got me
Does rt actually have something rendered to it?
Yes, it's got a camera rendering to it
What does your shader do?
Takes in a texture 2d and float for steps which is fed into a posterize node
The saving to a PNG was working when the active texture was the rt. So finalrendertexture must not be getting set correctly in the graphics.blit
I'd also be careful with when you call blit during the frame. The docs mention specific place for urp and hdrp, but I think there was such a constraint in birp as well:
To blit to the screen in the Universal Render Pipeline (URP) or the High Definition Render Pipeline (HDRP), you must call Graphics.Blit or CommandBuffer.Blit inside a method that you call from the RenderPipelineManager.endContextRendering callback.
I probably should have mentioned im in the standard rp
Yeah. That's why I mentioned birp. But then again, the docs don't say anything about it. Maybe have a look at the frame debugger and see if the blit command appears there.
Another thing to try is to serialize your final rt and have a look at it at runtime. Perhaps it's just a timing issue.
I have a question regarding steam achievements. I see that if I am not connected to steam, and a line of code that has something to do with SteamNET runs, it gives me an error. Does this mean I cannot build the game for other platforms like itch.io without having the game error due to it looking for Steam dependencies?
not sure if this a unity problem
You'd basically conditionally compile out anything steam related depending on the platform in use, such as #if !DISABLESTEAMWORKS, as well as the same thing on any steam-related dlls.
Is there any way to revert a property in all instances of a prefab in all scenes? I don't want to open every scene and manually revert for each prefab instance.
if you mean a serialized field, as long as it hasn't been overridden then simply modifying the prefab should be sufficient
https://docs.unity3d.com/Manual/PrefabInstanceOverrides.html
An overridden property value on a Prefab instance always takes precedence over the value from the Prefab Asset. This means that if you change a property on a Prefab Asset, it doesn’t have any effect on instances where that property is overridden.
this is a code channel
i write this normal map into another texture use my code, i get an incorrect result... I am wonder is my code problem or serialize problem
be more specific than "incorrect result"
i notice the preview normal in inspector is in wrong color
so have the first question
dragging the object into the slot in the inspector just serializes a reference to it, it does not change the object. most likely your code is wrong somewhere
Yes, that is true. Let me do some code research. Thank you for answer~
what is the kosher way to grab the camera nowadays? 🤔
Look for the MainCamera tag? .camera? DIY a solution?
(I am using cinemachine, if that helps)
Camera.main
public class PlayerCamera : MonoBehaviour {
private PlayerInput playerInput;
[Header("Camera Settings")]
[SerializeField] private float cameraSensitivity;
private float xRot;
[Header("Camera References")]
[SerializeField] internal Transform playerBody;
[SerializeField] internal Transform cameraRoot;
[SerializeField] internal Transform headIKTarget, armIKTarget;
private void Awake() {
playerInput = GetComponentInParent<PlayerInput>();
Cursor.lockState = CursorLockMode.Locked;
}
private void LateUpdate() {
Vector2 look = playerInput.lookInput * cameraSensitivity * Time.deltaTime;
transform.position = cameraRoot.position;
xRot -= look.y;
xRot = Mathf.Clamp(xRot, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRot, 0f, 0f);
playerBody.Rotate(Vector3.up * look.x);
}
}
I am trying to use a camera shake asset in Unity, but the shake does not work because I have synchronised the position of my camera to the camera root object. How can I solve this problem?
add a layer of indirection
make a "CameraRig" object with this script on it, and make the camera itself a child of that
private IEnumerator RevealCharacters()
{
while (_currentVisibleCharacterIndex < textInfo.characterCount + 1)
{
var lastCharacterIndex = textInfo.characterCount - 1;
if (_currentVisibleCharacterIndex >= lastCharacterIndex)
{
yield break;
}
char character = textInfo.characterInfo[_currentVisibleCharacterIndex].character;
TextBox.maxVisibleCharacters++;
if (character == '?' || character == '.' || character == ',' || character == '!')
{
yield return _punctuationDelay;
}
else
{
yield return _charDelay;
}
_currentVisibleCharacterIndex++;
if(TextBox.isTextOverflowing)
{
yield return _pageEndDelay;
TextBox.textInfo.pageCount++;
}
}
}
So I'm making a typewriter script which works by having the text already presented on the textbox, but revealed in increments. The problem I'm running into is that because it's being revealed and not dynamically appended to, I can't figure out when the text overflows so I can switch the page to the next. There's a few ways I can think of resolving this such as having my own escape character to prompt the page change, but I was wondering if I'm overlooking a method somewhere.
TextBox is of type TMP_Text
Ah, actually let me try some of these methods out. The problem is these documentations are just a little bare for how much is on them
Found a struct of information regarding the current page after digging around a bit more!
i have an object that i can pick up by clicking it, and rotate it by scrolling. i want to rotate it up and down, but if i rotate it on the x axis and look from the side it looks like im rotating it left and right. is it possible to make it so if im looking from the side it rotates it on the z axis and if im looking from behind/in front of it it rotates it on the x axis?
yes - this is all possible
could you give me an idea on where to start?
probably the dot product of normalized view vector and object would help
Is there any issue with keeping a static list of GOs/Components? Should still work just fine when switching scenes, right (of course all of the entries would be null though).
No need for a singleton component for the list?
you just said yourself what the issue is
when you switch scenes all objects are destroyed
Right... so it should all be fine then.
fine for what? I dont understand what your end goal is
Object Pooling
I mean..I would just make it a singleton so i can plug the items in the inspector 🤷♂️ then use DDOL to carry it over
since statics can never be exposed in the inspector, they belong to the class not specific instance
Yeah, I don't need to assign them in the inspector so all good.
Just remeber statics need to be manually reset
esp if you use Domain Reload off like myself
Ahh right, I always forget about Domain Reload being togglable, thanks.
hello lads, can anyone help me with finding up to 3 nearest objects toward the center of a trigger?
you could put them in an array and sort it by distance?
oh sweet, thanks for the idea!
Also you can might want to use Collider.ClosestPoint instead of transform.position when calculating the distance
taking a look at the framedebugger, i can see the blit been called. still black. when i checked its details i can see that the shader is been applied so the blit must be happening
@cosmic rain
long story short I'm pretty sure this is probably because your normal map isn't marked as a normal map in the texture import settings!
Unity encodes normal maps in a special way on import, and so any normal map field that should display normal maps, have to reconstruct normals from the encoded format. So, if the original normal map isn't flagged as a normal map texture, it will show up all weird in any inspector designed to draw normal maps specifically, like the one that's showing up in red
tldr is that on importing textures marked as a normal map, unity stores the red channel in the alpha channel, and ditches the blue channel entirely
(this is for compression/quality reasons!)
the blue Z channel is then reconstructed in the shader after unpacking, see UnpackNormal in UnityCG.cginc
Is it possible to derive from a Rigidbody in any other way or similar?
I want to be able to have an individual gravity on a per-object basis by extending Rigidbody, but it doesn't seem to allow me.
public class OrbitalActor : Rigidbody
{
public Vector3 GravityDirection = Vector3.down;
public Vector3 BaseVelocity { get; set; }
public new Vector3 velocity
{
get => base.velocity;
set
{
BaseVelocity = value;
base.velocity = value + GravityDirection;
}
}
}
I get this error “the script needs to derive from monobehaviour”
How can Rigidbody be added as a component then? Doesn't make any sense.
As Rigidbody does derive from Component
Yes, since it's not sealed
When does the error appear?
As I drag the script onto the gameobject
unfortunately components that you write have to derive from MonoBehaviour, unity does not support creating custom components that do not derive from that for whatever reason
That's a shame
actually i'm not entirely sure if that restriction is only limited to the editor. you could try adding the component at runtime instead of via the editor's AddComponent menu (though it seems like that may defeat much of the purpose of what you are attempting to do here)
I wonder why it isn't sealed then lol
Rigidbody2D is sealed whereas Rigidbody isn't lol
The 2d and 3d physics systems are entirely independent (and developed by entirely different people, I believe), so I wouldn't be surprised about discrepancies
Interesting, maybe something they missed?
I'm sure it's just limited by the editor
anyway, if that doesn't work for you, you could always just write a regular MonoBehaviour component that just adds force to the object every fixed update in your desired gravity direction and turn off the Use Gravity option on the rigidbody.
[RequireComponent(typeof(Rigidbody))]
public class CustomGravity : MonoBehaviour
{
public Vector3 GravityDirection;
[SerializeField] private Rigidbody _rb;
private void FixedUpdate() => _rb.AddForce(GravityDirection * Physics.gravity, ForceMode.Acceleration);
private void Reset()
{
GravityDirection = Vector3.Down;
_rb = GetComponent<Rigidbody>();
}
}
I figured it out, on my graphics.blit i set the pass override to 0. im not sure why its worked. wondering if you would and possibly could explain it. sorry for all the pings
how can i properly serialize a tree with newtonsoft? I believe there's some issues when serializing "Parent" since only the first node has a parent in the json file which makes sense since it would technically be infinitely "serliaziling." is there a workaround? https://gdl.space/pidejapiqa.php
My Intellisense in VS Community keeps breaking randomly? It usually works, but sometimes doesn't, per the snapshot - but it still has the 'references' text. Already tried clearing out .sln and .csproj files, and hitting regenerate project files - those seem to fix it, but then the problem appears again.
Unity 2022.3.45f1, Visual Studio Community 2022.
Any help appreciated!
whenever you go to regenerate the project files, do you find that you also need to assign visual studio as the External Script Editor again?
No, it keeps that fine
well then i have no idea what might be causing that issue. what you've described is usually caused by what I asked about which is fixed by launching unity as administrator and assigning that setting then relaunching
visual studio tends to JustWork™️ and provided you actually open it by double clicking a script in your project within the unity editor it should be able to load the solution and projects just fine
Trying to activate a gameObject while timeScale = 0. Is this possible?
When timeScale is set to zero your application acts as if paused if all your functions are frame rate independent. Negative values are ignored.
The implication here is pretty obvious, I did try it a couple different ways and none have worked so far.
show what you tried because SetActive has literally nothing at all to do with the time scale
Which is odd considering I thought that Update is frame-rate independent
well no, update specifically runs every frame. but unless you are doing anything that uses the time scale (like deltaTime), then the time scale is irrelevant
{
pauseMenu.SetActive(true);
Time.timeScale = 0f;
postProcessingScript.currentdepthIntensity = 0f;
GameManager.isPaused = true;
Cursor.lockState = CursorLockMode.None;
if (GameManager.usingController)
{
EventSystem.current.SetSelectedGameObject(pauseMenuBackButton.gameObject);
conNav.SetActive(true);
}
}```
My pause function. Trying to have the "conNav" activate if the player is using a controller. For some reason, conNav never activates under these conditions.
fixedupdate is what is frame rate independant
thats why its on the physics update
have you actually confirmed that the condition you are checking is true?
confirmin rn
and does conNav have any Animator on it that, say, fades in the menu?
Its animator is UnscaledTime
can anyone help me with this serialization/deserialization issue? the tree appears to be serialized correctly but when loading back in it seems like the NodeData of each node is being lost, specifically the GUID and unlocked state. https://gdl.space/yomacurede.cs, any ideas? everything else is intact and loads correctly it appears.
The one part I haven't tried is launching Unity as an administrator then setting VS in the preferences. I'll try it. But yeah, the scripts all launch visual studio whenever I double click them, even when intellisense is broken 😦
that would fix the issue i thought it might be, but is unlikely to do anything for the issue you are actually experiencing
Posting this question in this chat as well, since idk which one is best for this
I want to constrain a dynamic rigidbody to only move along a spline which I've sort of figured out how to do in two ways.
void FixedUpdate()
{
SplineUtility.GetNearestPoint(rail, rb.position, out var nearest, out float _);
transform.position = nearest;
rb.velocity *= Vector3.Dot(rb.velocity, transform.forward);
}```In this first method, I'm able to keep the rigidbody locked to only move along the spline, but collisions bug out frequently, at least when messing with things in scene view.
```cs
void FixedUpdate()
{
SplineUtility.GetNearestPoint(rail, rb.position, out var nearest, out float _);
rb.AddForce((new Vector3(nearest.x, nearest.y, nearest.z) - rb.position)*10);
}```In this second method, the physics are more stable, but the rigidbody isn't locked to the spline, it just gets pushed towards the nearest point on it.
Is there any better approach to doing this or am I missing something?
anyone willing to help?
Might have to do with the timing as I mentioned. Maybe the last draw call configured the GPU state to use non 0 render pass. In this case it would try to draw using a second pass in your shader, which presumably you don't have, so it doesn't render anything.
Though, that's a very big speculation.
Hi, I’m trying to make a game about trains where I build the tracks as the train moves forward. I wanted my tracks/rails to be prefabs with a portion of the track. I'm trying to use splines for this, but since they are different prefabs, their spline containers are different, and I'm unable to make the connection. Has anyone who has worked with splines figured out if these connections can be made?
Well, how are you serializing/deserializing it? There's literally 0 info about, and I presume it's not the default unity serialization (JsonUtility)?
I don't see why the first method would affect collisions in any way. Perhaps it's just moving too fast and doesn't have continuous dynamic collision detection?
As a basic example
that's the intent, yeah
If so, then obviously it would try to remain on the spline. The one causing the clipping is probably your cube, that is not moved by physics.
I plan on using XR Input to be able to move objects around, would that count as moving it with physics?
No clue. At the low level you can probably get the manipulators delta and use that to move objects in a physically compatible way.
You could simulate that by moving am empty object instead, and making a cube follow that empty object using physics.
apologies, here are my save/load functions https://gdl.space/omaxevozus.cs. im using newtonsoft
When you say that the GUID is lost, do you mean that it's being empty/null?
yes, its an empty string
when it gets deserialized
i assumed it was an issue with the PassiveNode class holding a reference to the parent but that is not being serialized since it would create an infinite loop
so I just reassign the parents by traversing the tree
What does the saved text file look like? Does it have the guids in it or are they empty there as well?
So the guids are serialized correctly
If they can be serialized, they can probably be deserialized as well. I'd try logging things every step through the deserialization process. Or even better, step through the code with a debugger.
i have, ill do some more but its just odd that thats the only thing not being deserialized correctly. no glaring issues?
I haven't used Newtonsoft serializer yet, so can't comment anything about wether its' correct or not.
What's ItemSaveData btw?
just a struct to hold al the relevent item/equipment data
its pretty clunky i assume i could do it better
but it works for now
{
public string GUID;
public PassiveNode treeRoot;
public GenericDictionary<string, Vector2Int> nodePositions;
public string randomName;
public RarityType rarity;
public int quantity;
public GenericDictionary<ItemStat, float> affixes;
public GenericDictionary<ItemStat, float> implicits;
public int itemLevel;
public int sellPrice;
}```
Did you try logging the guid value that it has on load?
public override void JsonLoad(SaveSystem system)
{
//pair of item instance and index
List<KeyValuePair<ItemSaveData, int>> data = system.LoadData<List<KeyValuePair<ItemSaveData, int>>>(savePath);
if (data == null) { Debug.LogError("Failed to load inventory"); return; }
for (int i = 0; i < data.Count; i++)
{
Debug.Log($"data {i} guid: {data[i].Key.GUID}");
ItemInstance item = ItemDatabase.RebuildItem(data[i].Key);
AddAtIndex(new ItemStack(item, data[i].Key.quantity), data[i].Value);
}
OnItemsUpdated.Raise(null);
}
Assuming you actually logged it and not making an assumption, the issue is probably in the deserialization.
Can't really help with that as I'm not sure what requirements Newtonsoft has for correct deserialization.
hm i fixed it by changing the property name from guid to nodeGUID, maybe there was some naming conflicts since the itemInstance also has a field named guid? no idea but weird issue
Possible
ah i actually figured out the real reason. In my class i have private fields and then public getters as such "public string NodeGUID => nodeGUID. These functions were being serialized and not the private field so when it was deserialized it wasn't able to change the value of the private field. For some reason this doesn't occur with reference types and I never encountered this before since I was always serializing SO's which had [SerializeField] attribute on the private fields. I have to mark the private value fields with [JsonProperty] for them to properly serialize/deserialize
Must be a part of how Newtonsoft's serializer works
guess so, any idea why it works fine with reference types?
i just went back and looked at your code, and what value types is it not working with? because the issue you seem to have is only related to reference types 🤔
i assume it might be because you can't just overwrite the value type directly as you can with reference types?
it was strictly an issue with the guid (String) and unlocked state (bool)
newtonsoft only serializes the public getters unless the private field is marked with JsonProperty
right and string is a reference type. the issue is not related to reference vs value types, it's specifically because that NodeData class has read only properties that you serialized, but had no way to deserialize them because the properties themselves were get-only (meaning they cannot be assigned to) and unlike the PassiveNode class you don't have a JsonConstructor specified that would be able to assign to the backing field
hm you're right
i forgot that string are referene types
well I got rid of the nodeData class and just have this in my PassiveNode class and the issue persisted, just trying to wrap my head around where I went wrong ```public class PassiveNode
{
[JsonIgnore] private PassiveNode parent = null;
private GenericDictionary<ItemStat, float> nodeStats;
private List<PassiveNode> children = new List<PassiveNode>();
[JsonProperty] private string nodeGUID;
[JsonProperty] private bool isUnlocked;
public PassiveNode Parent => parent;
public List<PassiveNode> Children => children;
public GenericDictionary<ItemStat, float> NodeStats => nodeStats;
[JsonIgnore] public string NodeGUID => nodeGUID;
[JsonIgnore] public bool IsUnlocked => isUnlocked;```
this works fine though
why bother with explicit backing fields here instead of auto properties with a private setter?
yeah that works too
of course
its just the way ive written all my classes though
i prefer this to auto properties
is it the same thing that would cause it here as well?
as you stated above
Just reading the serializer docs a bit, it seems to be serializing properties, and not fields. Might be wrong though. The docs are not making this clear from the very start.
yeah it does since in the json file it shows "Children" and not "children"
same for all of them
just throwing the JsonProperty attribute on the auto property would resolve that. then you won't have that attribute on a backing field and a JsonIgnore on the property
never noticed since i only change the capitalization
so instead of
[JsonIgnore] public bool Thing => thing;
[JsonProperty] private bool thing;
it would just be [JsonProperty] public bool Thing { get; private set; }
yep got it
and it does exactly the same thing as what you have, but shorter
And so you don't have properties that could be deserialized.
but how come i dont have the same issue with the other variables
children, nodestats, etc
because you have the JsonConstructor
ah makes sense
wait this? ``` [JsonConstructor]
public PassiveNode(List<PassiveNode> children, GenericDictionary<ItemStat, float> nodeStats, string guid, bool unlocked)
{
//Debug.Log($"Creating node with {children.Count} children, {nodeStats.ElementAt(0).Key} {nodeStats.ElementAt(0).Value} stats and {nodeData.NodeGUID} guid");
this.children = children;
this.nodeStats = nodeStats;
this.nodeGUID = guid;
this.isUnlocked = unlocked;
}```
yes
it also sets the guid and unlocked tho?
well yes, now it does. before it didn't so you had the issue
and also those weren't even part of this class in the previous code that had the issue
yeah ive been messing with things
but if i remove the [JsonProperty] attribute it breaks again
meaning the constructor is not what fixes it? or am i missing something
ah yes, because the ctor parameter's names are different than the property names
the only thing that can be different is capitalization afaik
ohh
so it should be string nodeGuid and isUnlocked for the serializer to properly match it?
in the params
yes
makes sense
see the example in the docs: https://www.newtonsoft.com/json/help/html/JsonConstructorAttribute.htm
The constructor is for deserialization. Properties are for serialization. You need both ends working correctly.
makes a lot of sense, didnt know about the matching params thing
appreciate it
also makes sense why when I tried to use [JsonIgnore] on the parent variable it wasnt working
has to be used on the getter
Does anyone know the behavior for when a 2d raycast passes perfectly through:
a) A corner of a collider, but not into the bounds of the collider
b) Parallel and on the same plane as an edge (eg, an edge defined with points (1,2) and (2,2) and a raycast from (0,2) directly to the right)
Does this just depend on floating point precision? Like a liiiittle to the left or right will just be 50/50 on whether it hits or not?
How can it pass through the corner without hitting the bounds?
Yes. It's gonna be up to a floating point error and possible would provide different results in different situations.
Yeah idk lol, I'm trying to follow this article and I don't know how to reliably cast a ray through a corner point. https://www.redblobgames.com/articles/visibility/#wall-tracking
Well, there's gonna be a precision limit no matter what you do, so it's fine if there's a small error in the detected wall position.
I see, so maybe I should just add like 0.001 radians to my angle and raycast for the next wall?
What part of the article are you talking about exactly? Are you just casting a ray every few angles or what?
what are you actually trying to solve as well? because you should basically never have this problem
Trying to make a visibility polygon like in the article, and I have the points numbered in radial order but I don't know how to proceed in raycasting from edge end points to the next closest wall.
No, I'm doing the approach where I draw triangles between all the points in the scene
What's the problem with just casting a ray from that corner position?
How do I create a function that will accept a generic struct and search for specific type in that struct?
I want to loop trough a List<struct> and find Image or other component and delete a game object assiociated with it.
The reason I want it generic is so it's not dependent on custom class/struct(it's for my Helpers functions that can be reused)
As an example(which perhaps can be improved?)
public static void DestroyAllChildren(Dictionary<string, Image> dict)
{
foreach (Image child in dict.Values) Object.Destroy(child.gameObject);
}
public static void DestroyAllChildren(Dictionary<string, SkeletonGraphic> dict)
{
foreach (SkeletonGraphic child in dict.Values) Object.Destroy(child.gameObject);
}
I need something similar but for a custom struct which will contain either Image or SkeletonGraphic in my case, but the helper method won't be aware of what struct I have passed.
I need a struct to allow duplicate "keys" so I can't use dictionary anymore.
(It can also be a class instead of a struct if that makes it easier)
those structs need to implement a shared interface or base type for that purpose that exposes the fields/properties/methods you want to call. Alternatively you can test if an ‘object’ is of a certain type. A generic type argument doesn’t really help you there without the objects having something in common to operate on.
if you want to use structs you will need to use an Interface. Classes could use an Interface or a common parent class
I want to avoid having shared type, unless its a built in one, since inn another project that struct wont exist anymore and my Helper class would throw an error
Then it’s not possible in a type safe way
so I have to loop through struct in my code directly and delete objects from there?
Is there a different way to set it up to allow for my helper class to handle it?
I guess that I can create a List out of the struct then pass it to my Helpers class
All it needs to do is destroy gameobjects
I could also probably just swap the order Dict<Image, string> but that feels wrong.
that makes no sense
the issue is that <string> is duplicated
What do you actually want to implement that needs this kind of thing?
if your helper class is being shared across projects why not just include the interface in the same code file?
I am saving tags with an image, so they can be cleared from the list, tags are saved to json so I can recreate the scene on game load.
Tags have all information to recreate the image.
if we try to draw same image twice without removing it first from the Dictionary, it throws an error for a duplicate key.
I can fix my issue with this:
foreach(ImageTags image in DisplayedImages)
{
Destroy(image.image);
}
foreach (SpineTags spine in DisplayedSpineFiles)
{
Destroy(spine.skeletonGraphic);
}
I was just looking for a cleaner way
if that is all, then fix that code
So I can do what I did before:
Helpers.DestroyAllChildren(DisplayedImages);
Helpers.DestroyAllChildren(DisplayedSpineFiles);
Yeah but we might want to have duplicate tags in some cases in the future
the one case I can imagine is if we add random property to the tag which would make sense to have more than 1 of these.
otherwise if the tag is the same with specific values then it doesn't seem to make sense to have duplicate, I agree.
Its for an Inky game
we parse tags from the json file that gives them to us as the story progresses.
I need to save them so I can recreate the scene with correct images on the screen, music playing etc.
by random I meant like
#particle:asset'bubble',random'true',minSize'5',maxSize'15'
You could add those particles multiple times in a row and it would make sense(they would cover more and more of the screen, but also be random)
Thats kinda the edge case, but I am sure there might be more to come
if you need duplicates then use
Dictionary<string,List<interface>>
How does that work? string cant be duplicated right?
no,, you add the duplicate to the List
oh
that almost works, but they need te be in order they were added
so when scene is recreated they are at correct z depth.
Even tho we have z depth already, but if we have 2 images on same z depth they will appear based on the order they were created.
But thats close 😄
Maybe a List of Tuples?
List<Tuple<string Image>>
not sure the syntax, but that might be what I need
Then make it a list of containers instead of a dictionary.
what are containers?
It kinda sounds like what you need is sort of a parser
Like a tuple basically?
Just a class or struct that would contain the data you want.
yes thats what I do now
Like your string and a list of whatever
but then the struct is not generic enough to put a script in my Helpers class
Which was my main reason for this question
Make it generic
//NEW
foreach(ImageTags image in DisplayedImages)
{
Destroy(image.image);
}
foreach (SpineTags spine in DisplayedSpineFiles)
{
Destroy(spine.skeletonGraphic);
}
//OLD
Helpers.DestroyAllChildren(DisplayedImages);
Helpers.DestroyAllChildren(DisplayedSpineFiles);
That code doesn't tell me anything without knowing the context
I was told it's not possible the way I do it, is there another way? A way that doesn't make a Helper class be dependant on a custom class/struct?
You'll need to provide more details on what you're currently doing and what you're trying to achieve.
ah yeah sorry, the Old version used a Dictionary<string, Image>
Where did it use it?
Ok, let me write it down
werent you told its possible just using an interface or base class? i skimmed over the convo a bit but its really unclear whats actually stopping you from making this work
Those are from my helper class, that I can reuse in multiple projects which have different scripts etc.(so same custom class/struct won't appear in other projects)
public static void DestroyAllChildren(Dictionary<string, Image> dict)
{
foreach (Image child in dict.Values) Object.Destroy(child.gameObject);
}
public static void DestroyAllChildren(Dictionary<string, SkeletonGraphic> dict)
{
foreach (SkeletonGraphic child in dict.Values) Object.Destroy(child.gameObject);
}
If it requires understanding many script relationship in your project, maybe just upload it to GitHub and share the link.
I think its quite simple, there are just 2 versions to show so there will be few lines of code, but I will try to keep it simple
My custom class that runs game logic etc:
Dictionary<string, Image> DisplayedImages = new();
Dictionary<string, SkeletonGraphic> DisplayedSpineFiles = new();
public void RemoveImages()
{
Helpers.DestroyAllChildren(DisplayedImages);
Helpers.DestroyAllChildren(DisplayedSpineFiles);
DisplayedImages.Clear();
DisplayedSpineFiles.Clear();
}
That's the old way
But <string> cant be duplicate, so now I need a way that allows for duplicate string, but also let me use my Helper class methods(I can make a new method if it works without having a custom class dependency in the Helpers class)
Wdym by "can't be duplicate"?
So someone did mention to use UnityEngine.Object I believe as a base class.
you can't add same key to the dictionary twice.
but I have a case where it might happen
Indeed. maybe a string is not an appropriate key then.
Which is why I am trying to fix it.
So my curent fix is to use a List<struct> which is fine, but I can't use Helper script anymore as it would be dependant on my custom struct.
How are you discerning between different keys if they are the same string?
I don't, just got this issue so I am looking for a way to fix it.
The fix is simple if I ignore my helper class, I just wanted to know if there is a way to keep it 😄
Maybe make your helper mwthods generic then.
Helper.GenericMethod<Type>(param);
public struct ImageTags
{
public string tag;
public Image image;
}
public struct SpineTags
{
public string tag;
public SkeletonGraphic skeletonGraphic;
}
List<ImageTags> DisplayedImages = new();
List<SpineTags> DisplayedSpineFiles = new();
Yeah but doesn't that mean I have to give it a correct type?
or is "Type" a generic type?
I know there is T, but I used it very rarely so I can't remember now
You do yes.
So that means my Helper class will be dependant on having that type in the project right?
T is just the name you can give a generic type
So that's what I want to avoid.
Yes.
Because I want to use my helper class in other projects.
and I don't want to bring those structs/classes with it.
Well, it's kinda silly. You're trying to avoid something fundamental to how C# works
this helper functionality honestly looks so specific to your use case, i dont see why you would even worry about using this in other projects
It's like, you want to eat, but you refuse to open your mouth
if both of your target objects are Monobehaviours why not use that instead of Image or SkeletonGraphics
What do you mean? I just want to reuse a helper script that handles Unity related work.
I am already using it, trying to slowly build on it
If they are generic, you should be able to reuse them as is.
Maybe its silly, idk we will see in the future 😄
Yeah I am thinking of doing that, then I can just GetComponent in my script if I need to get specific data
no need, just cast it
as long as I keep Image/SkeletonGraphic on separate list
If you use generic constraints(which you'll probably need to do if you want access to specific fields), then they would only depend on that constraint. You can't avoid that.
So in my head I was thinking of having a way to loop through a List of "struct"(generic) and search its properties for specific type(Image, SkeletonGraphic)
But maybe that's not a thing, or a bad practice
i mean the original helper function you had used a dictionary, and then proceeded to ignore the actual part of it being a dictionary because you wanted to just destroy a list of gameobjects.
the same thing applies here to your structs, this seems so very specific to a structure in your code that i dont see a reason to actually need this as a helper function. It sounds like you just want to destroy a list of objects
public static void DestroyAllChildren(Dictionary<string, Image> dict)
{
foreach (Image child in dict.Values) Object.Destroy(child.gameObject);
}
This is looping through dictionary
That might be possible with reflection, but this whole approach sounds weird to me. I wouldn't recommend that.
this isnt really a helper function anymore, just a way for you to save 3 lines and have really questionable code elsewhere
are you reading the messages im writing? posting your code in response to my message makes literally no sense. its just proving what im saying about the code..
yeah, but in my other project I had a foreach loop to destroy objects written in many places, so I decided to add them to a helper class to reuse
Yes, but I am still not sure what do you mean, you are correct, I am trying to destroy a List of game objects.
They mean that there's basically no point in making it a dictionary. Just use a list of gameObjects
What do you mean by "you had used a dictionary, and then proceeded to ignore the actual part of it being a dictionary"?
I need to keep <string> connected to <Image> on my side
But yeah, I can just recreate a List<gameobject> and destroy them too.
look at the helper function, its not actually using the dictionary. it just wants a list. this is why i say this helper function is extremely specific to your structure.
I don't understand, it's asking for a Dictionary
The point of that is that my project might have a different structure, like Dictionary<string, Image> or now List<struct>
Because of my needs, but the helper function doesn't need to know that, if I pass a Dictionary to it, it just needs to loop through it and remove gameobjects.
Is it wrong approach?
If the only thing you're worrying about is the line count, you can just use linq to write it all in one line.
dictionary.Select( x -> x.gameObject).ForEach( x -> Destroy(x));
Yes, but then I need to remember that line and write it everytime I want to do a simple task of removing gameobjects from a List/dict/struct
Maybe that's fine idk, I just liked the way of typing Helpers.DestroyAllChildren() and pass different data type for it to handle it.
public static void DestroyAllChildren(Transform t)
{
foreach (Transform child in t) Object.Destroy(child.gameObject);
}
public static void DestroyAllChildren(List<GameObject> objects)
{
foreach (GameObject child in objects) Object.Destroy(child.gameObject);
}
Is it that bad? 😄
If you want it to be generic, then you'll need to abide by the rules of C# generics.
It is fine unless you have hundreds of these variations.
Well, GameObject is not a built in type, so you're already stuck
Because built in types are shared in other projects, so thats 100% good for me
GameObject is part of Unity right?
So that's a built in type for me
Then create a type that would be shared in all the projects
C#/Unity, just not custom struct/class that I created.
haha thats actually...a good idea
If you're creating a framework for several projects, obviously you want your own types that would be considered "built-in"
Since I am already using a Helper class, I might as well have a Helper List of things I tend to use often
Yeah that seems like a good idea, I might need to start building those.
yes, and thats what im saying about your helper functions. yes it takes in a dictionary, but only because your structure wants it to. What if one day you have a new structure of gameobjects? suddenly your helper function would need to be added to. Again this is very very specific to your structure and seems like you're just are trying to save lines
My approach was: If I do something often, I should write a helper script for it.
And you can make it abstract enough by just sharing interfaces.
If you're doing something often, then you should rethink your system architecture.
When I am tired and I can't remember how to check if index is within a range:
public static bool NumberWithinRange(float number, float minRange, float maxRange, bool inclusive = true)
{
if (inclusive)
{
if (number >= minRange || number <= maxRange) return true;
}
else
{
if (number > minRange || number < maxRange) return true;
}
return false;
}
But if you need to delete children from a gameobject, what can I do better to not write that code in different UI scripts?
if i dont delete them, then I disable them. I still have repeated code.
If you have the same pattern in many places, it's a good place to use a base class.
im not sure how many different places you're destroying children objects from, but id really only have helper functions in places that you're either doing complicated stuff or they're at least a few lines long
even that NumberWithinRange function, id consider how often you're really using it.
oh, that seems like a good idea too, I should probably have base UI class for my UI managers to handle that.
Good call!
Or rather a "UIList" or something class.
Yeah I didn't really have a good reason to add it here, other than when I work late hours and I can't focus on counting if(index < arr.Length) return;(not in range) then I decided to write a helper script for it haha
Yeah I should have a base class for my UI classes that share some of the functionality.
`using UnityEngine;
public class PlayerShooting : MonoBehaviour
{
public GameObject bulletPrefab; // The bullet prefab to instantiate
public Transform firePoint; // The point where bullets are fired from
public float fireRate = 0.5f; // Fire rate in seconds
private float nextFireTime = 0f;
void Update()
{
// Get the mouse position in world space
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0; // Ignore Z axis for 2D
// Calculate the direction between the gun and the mouse position
Vector2 direction = (mousePos - firePoint.position).normalized;
// Rotate the gun towards the mouse
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
firePoint.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
// Shoot when the left mouse button is pressed and cooldown allows
if (Input.GetMouseButton(0) && Time.time >= nextFireTime)
{
Shoot(direction);
nextFireTime = Time.time + fireRate;
}
}
void Shoot(Vector2 direction)
{
// Instantiate the bullet at the fire point
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
BulletMovement bulletMovement = bullet.GetComponent<BulletMovement>();
// Set the bullet's direction
bulletMovement.SetDirection(direction);
}
}`
i told chat gpt to make me an bullet script but everytime i press click it dosent shoot pls anyone
and this is my bullet script
`using UnityEngine;
public class BulletMovement : MonoBehaviour
{
public float speed = 10f;
private Vector2 moveDirection;
public void SetDirection(Vector2 direction)
{
moveDirection = direction.normalized;
}
void Update()
{
transform.Translate(moveDirection * speed * Time.deltaTime);
}
// Destroy the bullet after a certain time or when it goes off-screen
private void OnBecameInvisible()
{
Destroy(gameObject);
}
}
`
im making a 3D shooter game rn, working on interactions. I have my Interact() marked as override but it still gives me this error:
Assets\Scripts\Interactables\Keypad.cs(18,29): error CS0506: 'Keypad.Interact()': cannot override inherited member 'Interactable.Interact()' because it is not marked virtual, abstract, or override
any help?
The error you're seeing means that the method you're trying to override in your Keypad class is not marked as virtual, abstract, or override in the base class Interactable. To fix this, you need to ensure that the base class method is properly set up to be overridden.
how to do that?
Base Class (Interactable)
public class Interactable : MonoBehaviour { public virtual void Interact() { } }
Derived Class (Keypad)
`public class Keypad : Interactable
{
public override void Interact()
{
}
}
`
Is it possible to make protected override void Interact()?
Derived class
But I did the thing and it gives me the error
wait lemme give u another script
Base Class (Interactable)
using UnityEngine;
public class Interactable : MonoBehaviour
{
protected virtual void Interact()
{
}
}
Derived Class (Keypad)
using UnityEngine;
public class Keypad : Interactable
{
protected override void Interact()
{
}
}
looks like an AI answer, and likely is considering in the message above you said you used AI to code. please dont "help" anyone by just pasting shit from a spam generator
ight
show the Interactable class
using System.Collections.Generic;
using UnityEngine;
public class Keypad : Interactable
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
protected override void Interact()
{
Debug.Log("Interacted with " + gameObject.name);
}
}```
btw could u help me also?
maybe reread what i asked you to show, thats not the interactable class.
just as a note, this error is very clear on what it actually wants you to do. You'll need to mark the method as virtual or abstract. you choose either one depending on if you want it to have any default implementation or if you force derived classes to implement it
Do you understand the code that was generated for you or did you mostly drop it in Unity, hook some things up and tried to test it?
so the first time i coded by a yt tutorial nothing worked and told him to help me and now it dosent shoot and when i enter game my bullet prefab just dissapears or turns in a object and the game is 2d btw
Alright, that sounds like a good description of the problem, but do you actually understand the code that you are using?
not really cause i just started the script but i understand some things of it cause i watched some tutorials and can understand a little
The problem with AI generated code is that it doesnt really understand C# or Unity, its pulling a bunch of text from online resources to generate a response that sounds like what you want to hear, and without understanding the code it gives, it would be difficult to provide help - maybe you could try adding some breakpoints or Debug logs to figure out what the code is doing, or what I usually do is take a step back and break down the goal into small steps, then try to figure out how to build and test each step till you get something functional - AI code is great for ideas but will rarely work "out of the box" from what ive seen
👍 thanks bro il go check some tutorials
have a good day/night
Well my suggestion was more debugging and breaking down the problem further, but if you want to try more tutorials you can give that a shot too
hey guys, how can i search for a specific class that is a child of another class? basically i have Health, Stamina and Mana classes and a parent class Status. so for example i want to find if i have Health component , how do i specify that in the function?
If you specifically know the class you want to find is Health you could check if _status.GetType() is equal to that specific typeof(T), where T in your case may be Health - another option is to use a abstract or virtual function (or possibly a interface) in Status so you wont need to know specifically if its Health, but Health can override that function for whatever it needs to do
public Status GetStatus(int _status) {
Status _stats = null;
switch (_status) {
case 0: _stats = statusFolder.GetComponentInChildren<Health>(); break;
case 1: _stats = statusFolder.GetComponentInChildren<Stamina>(); break;
case 2: _stats = statusFolder.GetComponentInChildren<Mana>(); break;
}
return _stats;
}```
this is my solution for now
the problem is the parameter
i want to specify there so i can remove this switch from the function
Maybe its not clear the purpose of this function, even if you changed your int param to a Status param, youd probably still be checking the type with something like if(status.GetType().Equals(typeof(Health)) { ... } else if(...) { ... } which, if you plan to add more than those 3 types, this approach can over time become difficult to manage
if the status is not existant in the folder then it wuld just return null
How can I render a camera's view on top of another camera? I'm trying to have some objects rendered separately, but I can't get the camera for those objects to actually show something. I'm using the built-in Render Pipeline
I got it to render to a RenderTexture properly but I have no idea how could I show it on-screen
Maybe you could have your status folder have a bool-returning function that checks the type its passed as a param, then whatever needs to use it can simply ask the folder if it has a certain type or not rather than checking all your types
how wuld i ask if it has a specific type?
RenderTextures can be used to show what a camera sees on UI, and a RawImage component can accept render textures as the "sprite" - unless your goal is to layer cameras in the game world and not on UI so for example camera A shows object A but not object B, and vice versa for camera B (some FPS games do this to render the weapon on a different camera than the character to avoid clipping through the game world, that is a bit different than showing what a different camera sees on UI though)
status folder could either keep track of its children type and you can use a list or something similar to compare, or you could use your GetComponent call and check if its type is the same as your params type, or if your GetComponent returns null using the param type for the GetComponent call, there is also GetComponent(Type t) instead of GetComponent<T>() which does the same thing but lets you pass a object/param instead of a direct type
yes but how can i specify in parameters what type am i looking for?
The same way you originally had, they all derive from the same base type so your param could be Status someParamName then you check against/with someParamName for the underlying type
hello im trying to build my game but it gives me an error about a script i didnt even know existed. https://gdl.space/dagiqujete.cs