#archived-code-general
1 messages ¡ Page 248 of 1
public int Defense
{
get { return (int)((CharacterSO.BaseDefense + _Defense) * (Character.HasStatus(StatusEffect.Restrained) ? 0.5f : 1f)); }
internal set { _Defense = value; }
}
Like this?
I do calculations on floats, then return an int
thing is if you have like % modifiers you're not always going to get an int, so you need to either decide to round up or down
It automatically rounds down right?
however you want to do it
At most I lose 1
so its fine I think
wait I dont need to store them as floats
if I multiply float * int it returns a float right?
public int Defense
{
get { return (int)((Character.HasStatus(StatusEffect.Restrained) ? 0.5f : 1f) * (CharacterSO.BaseDefense + _Defense)); }
internal set { _Defense = value; }
}
right, but sometimes you may want to have float values like attack speed
yes those will be done differently I think
This is for attributes, tho we dont even have attack speed so its fine.
I've got a lot of my stats in a dict so having them all as a single type is easier to deal with
enum to ref
it works pretty well for a simple implementation
This is how I do it atm
I will just add extra calculations inside and call it a day
probably not the best, but each stat has different formula
Having the setter set a base value but getter return a modified value is often a bad idea
BaseHit cannot be changed, but Hit can.
I was thinking of having a separate getter like "DefenseTotal"
Not sure if necessary tho
I only want to change "_Speed" and return a modified "total speed"
i.e. when character levels up they gain +2 speed
but if you do Speed += 2 it won't do what you'd expect it to do
I can imagine this being an issue when saving or loading
or even when displaying value on the UI(full value without modifiers)
That makes sense, I might need to separate those
I suppose this might work better
public int Defense { get; internal set; }
public int TotalDefense
{
get { return (int)((Character.HasStatus(StatusEffect.Restrained) ? 0.5f : 1f) * (CharacterSO.BaseDefense + Defense)); }
}
I set Defense on level up
I keep the getter in case I want to get base value, but its not ideal already as I should also have BaseDefense there.
Perhaps I will get rid of it and do it on level up from lvl 0 to lvl 1
I've done something similar in the past. Though, I think you may want to figure out a way to cache values a bit more instead of recalculating them if your game becomes a bit more complex later on.
I do something similar such that I listen onto stats that become dirty instead of directly recalculating values everytime I am attack or attacked.
funny thing too is that I want to rid of all my events and just make my own subscription model since they generate so much garbage
specifically for stuff like my abilities and gameobjects where I've a lot of pooling going on.
Makes sense, I just like the idea of properties as VS will show me "references" which I find useful.
If a need arises I will look into optimizing it, definitely will be using UnityEvent to update UI when a value changes.
Which won't be easy to do as some values depend on buffs/debuffs.
Hi! Does anyone know how can I put a little menu in the game view? Like for displaying fps, or player speed/state, buttons, switches etc.
by making an ui
Like this one
this is on gui iirc
Ah okay :D
My mistake. it should have been ClassExtends, not TypeExtends. TypeReferences has various different constraint attributes to work with.
ClassTypeRefrence holds a refrence to the type as an object of type Type (and can be implicitly cast to a Type). In this case you want to make an actual instance of the type like this:
private MyStrategyBaseClass strat;
...// Whenever powerup state changes...
strat = Activator.CreateInstance(myScriptableObject.myStrategyField) as MyStrategyBaseClass;```
Here, the Activator makes a new instance of that type (as type object), and then we cast the object to a type that we know it extends.
Fyi, if you needed to do this with a class that extends MonoBehaviour, AddComponent can take an argument of type Type as well. Example:
```TileMonobehaviour tileMono = tileGameObject.AddComponent((Type)mySO.tileMonoTypeRef) as TileMonobehaviour;```
I'm super confused at how any research papers are able to compare two crowd simulation algorithms against eachother in terms of actual speed it takes for the agents to reach certain goals (basically evaluate how well they move about and dont get deadlocked). Speed of agents is not standardized among various algorithms so you can't just say "put the same speed for the agents on both algorithms". And also, complexity of the algorithm also slows down the speed of the agents.
Hey,
I'm trying to use Unity ECS system for the first time using the example with the spawner but I'm a bit confused on how things work
I tried to make a player that have a Scriptable Object with its info
public struct Player : IComponentData
{
public PlayerInfo Info;
}
public class PlayerAuthoring : MonoBehaviour
{
public PlayerInfo Info;
}
public class PlayerBaker : Baker<PlayerAuthoring>
{
public override void Bake(PlayerAuthoring authoring)
{
var entity = GetEntity(TransformUsageFlags.None);
AddComponent(entity, new Component.Player
{
Info = authoring.Info,
});
}
}
But I'm getting this error:
CS8377 : The type 'Player' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'IBaker.AddComponent<T>(Entity, in T)'
Would someone please know what it means, and optionally is there some other good examples available online (that aren't too complex)?
if youâre looking at research papers, I would check their methods
iâm not sure how well versed you are in reading journal articles, but this should be relatively simple
you must use unmanaged type (non-nullable value type), and ask in DOTS general discussion
Will do thanks
Hey guys I am making a quiz game in unity which , when a user selects the correct answer it makes the option green and then question changes but when the user selects the wrong option it gets wrong and the right answer gets green then there is a delay and after which it changes the question , So i was thinking how can I produce this kind of behaviour
What's exactly what you don't know how to do about that? It sounds pretty simple
What's a go-to noise library? I'm making a minecraft clone
hey guys, I'm designing my mobile game's UI and I wonder which is the lowest screen resolution I should design for? I've been working on 800x400 portrait (yes, it's forced to be portrait) provided by unity, but when arranging some stuff they simply don't fit into the screen (with other game components) or they are too small for larger screen resolutions. I already know about canvas scaler and configured it to my needs, but the problem persists so I wonder if people actually use 800x400 phones
if you work with phones, do research on aspect ratios
iâd focus on aspect ratio first. then common resolutions, and look for greatest common denominator
good hint, thanks
it just sucks to not use full space on tiny phone screen because an app was made for a different aspect ratio
so you get the black bars
Im trying to get my camera to smoothly lag behind the player a little bit, but when I lerp (and slerp) the positions like so:
Camera.main.transform.position = Vector3.Lerp(Camera.main.transform.position, new Vector3(transform.position.x, transform.position.y, -10), 0.2f);
I get a jitter:
how can I get the camera to lerp and not just be hardclamped?
i gave my camera a kinematic rigidbody, and use MovePosition
i let physics system take care of the interpolation
hmmm
ok
you still need to lerp, but MovePosition will take care of the in between frames better
how does the player move?
Camera.main.GetComponent<Rigidbody2D>().MovePosition(new Vector3(transform.position.x, transform.position.y, -10));
like this?
my camera also has like 6 different collider objects on it, so it makes sense
i think using cinemachine is better, there is no need to reinvent the wheel
answered to wrong message
b-but I love re-inventing the wheel...
then suffer quietly đ
my camera has a solid hitbox so player can get crushed by autoscroll, death hitbox if the player falls off screen, spawn hitbox to trigger spawns, visible hitbox to trigger things when they become visible, and despawn hitbox to despawn things when far
my game is a 2D sidescroller, so this makes sense for me. does not make sense for 3D
it is still jittering with this code, I tried with both having and not having the lerp
oh
and moveposition should also operate on the rigibdody
yes
is rigidbody set to interpolate?
hmm that just makes it instant
when you say "you still need to lerp it" what exactly does that mean?
hmm?
ill check
ah it isnt
that just makes it jitter again
actually, interpolation probably only matters if you have colliders
yeah no colliders
every fixed frame, MovePosition should go to Lerp(currentPosition, targetPosition, lerpValue)
ohhh
Interpolation shouldnt care about colliders or collisions, it just smooths the appearance of the movement
i forget which interpolation mode it is. Continuous detection is the one that actually casts the rb colliders to check collision, as opposed to smoothing movement
i donât recall which setting is which
but one controls that, and one controls the other
yup,, got it to work
Ah, you meant collision detection mode. Interpolation modes doesnt affect collisions
ah, right. getting mixed up
interpolation must be on
collision detection mode is irrelevant without colliders
Yeah
interpolation doesn't seem to need to be on
either way, all is well that ends well
Gives me an error as well sadly 
thatâs weird. do you not have the ClassConstraints file from TypeReferences?
eg did you import the package, or did you find a single .cs file and add it to your project?
I added it via the package manager through git url
I followed the little tutorial on the link you sent me yesterday
look for a file called ClassConstraints or something.
if you Ctrl shift R on the TypeReferences namespace, it should show you all lines of code using it in your project
ClassConstraints doesn' appear to be in the package
I wonder if I maybe have a different version of the package? If your Inherits attribute works, then that should be it
Yeah Inherite doesnt give any errors
ok, it must be a version difference
Yeah
I'm trying to implement this now
I hope I can make it work
given the type of game you are making, I can say with confidence that this exact pattern is almost guaranteed to appear again
i also see that my version of ClassTypeReferences is the old inactive one. the one I linked you forked from it, and is currently maintained
Nice
So the MainPlayerMovement is a seperate script right? And a method to create an instance of the current playerMovementStrategy is called whenever we grab a different powerup?
Ah nevermind I got it, but just like before, the HandleMovement script gets called, but my character still doesnt move somehow
So instead of adding up the velocity here, it just sets it to the first value the entire time and stays that way:
velocity.x += inputDir * physicsConstants.initXAccel * 2;
This sets it to 0.75 and stays the same value

Here is the debug in the console:
Any ideas why?
show the full code. What are you actually logging?
Nevermind I got it đ
Hey, let's say I have 2 tilemaps, "WallMap" which defined floor and wall where the player can collide with and "TrapMap" that contains traps which when the player collide with, loose
I'm using RuleTile to place my walls and it's working well, but I would like to do the same for my traps (which are on the TrapMap) but for them to depend of "WallMap" for rules
Like in my screenshot I want the trap sprite to use the "down" version since on the "WallMap" there is some floor there
Is it possible to do that?
i assume the issue was trying to assign x component, instead of assigning a whole new vector to rigidbody velocity
yes it is possible, but it takes a bit more work
you need to define a custom ruletile class, where in the neighbor check function it gives you the coordinate being checked
and you need a way for your custom ruletile to get a reference to the map you want to check
i can send you code in a bit. it was obnoxious af that Unityâs custom ruletiles donât automatically pass you the coordinate
That would be nice of you if you could, thanks :)
give me like half an hour
I had to pass in the ref keyword for the velocity, which made it work
ah. you were modifying a copy of velocity
Yeah that was pretty dumb of me lol, but Iâm glad it finally works now. Thanks for all the help btw!
sure
one last thing before you go: I recommend seeing if you would rather make your PlayerMovementStrategy an interface instead of abstract class.
interface gives no default implementation, but allows it to be tacked on to other classes involved in other things
Hmm yeah I was thinking about changing it already. Itâs probably better with an interface
main benefit of abstract class is having a default implementation (eg standard Jump()) that all children inherit by default.
benefit of interface is allowing class to be held by PowerupManager and engage in different things beyond player movement from one class.
eg FireMario : PowerUp, ICustomRunButton, IPlayerMovementStrategy, and then that class might contain logic for both playermovement and throwing fireballs
you might also consider composition:
public PlayerMovementStrategy strat;
âŚ}
public class PlayerMovementStrategy {âŚ}
public class FireMario : PowerUp {âŚ}
public class FrogMario : PowerUp{
public class FrogMovementStrat : PlayerMovementStrat {âŚ}
âŚ}
I got it, but it's 275 lines of code, most of which are really specific to my project
I wouldn't mind having a look if I can see the logic behind it and try to adapt it to mine
ok, so, here is how I did it. There are 3 main classes
CustRuleTileStatic has references to things that are important for evaluating the ruletile that only exist during runtime. Example: References to Tilemaps
Hi! How can I load and save a file in unity cloud form cloud code?
CustRuleTileBase<TNeighbor> contains a VERY important override to the CheckRuleTile method that gives us the coordinate being checked. This class ALSO gets ALL rule logic. Every single rule that you can include in a custom ruletile goes here
do NOT define actual logic for a type of rule outside of this class, and you'll see why next
I just committed with the important 3rd class: CustRuleTile : CustRuleTileBase<CustRuleTile.Neighbor>
Why does my elixer sprite not show up in my game view, even though it exists in the scene view?
because you're trying to position it relative to some UI elements
meaning it's there - it's just way up and to the right
CustRuleTile has it's own neighbor class which just contains constants for different neighbor rules. CustRuleTile : CustRuleTileBase<CustRuleTile.Neighbor> so that the rule tile methods know to use this neighbor rule
SpriteRenderer is not a UI element
Wdym by "way up to the right"?
physically
it's not in veiw of the camera
AND it has public override bool RuleMatchCoordinate(int neighbor, Vector3Int currentTileCoord, Vector3Int targetTileCoord) {....
which is the function that funnels different rules to different logic via switch case
if you're trying to make a UI element, you need to make it a UI IMage
not a SpriteRenderer
Thanks, I'll save all your explanations in a notepad and have a deeper look at your code
Thanks! I think it works now
I just committed my explanation into a big comment at the top of the code file
Thanks a lot
Zirk
sure. I just modified again. it was clearly not super ready to share lol
RaycastHit hit;
Physics.Raycast(_groundChecker.position, transform.TransformDirection(Vector3.up), out hit, -100, _groundLayerMask);
Debug.DrawRay(_groundChecker.position, transform.TransformDirection(Vector3.up) * -100, Color.yellow, 10);
groundDistance = hit.distance;
Debug.Log(hit.distance);
why does this always give me 0 ?
the black plane has the Ground Layer, which is assigned in the inspector to _groundLayerMask
-100 is not a valid max distance
oh
instead of transform.TransformDirection(Vector3.up) use -transform.up
and use a positive number
how do i tell to go to the opposite of up then ?
I just told you
sorry didnt saw
ty
If you want to modify the animation clips in your animator without changing the state machine, the recommended solution is an Animator Override Controller:
https://docs.unity3d.com/Manual/AnimatorOverrideController.html
https://docs.unity3d.com/ScriptReference/AnimatorOverrideController.html
Thank You â¤ď¸
Anyone knows how to do sliding properly? I tried the line below, but that just teleports the player forward, I tried setting the drag to zero and all other modes in ForceMode.
rb.AddForce(bodyRef.forward * slideStrength, ForceMode.Force);
AddForce should never teleport
Force mode AddForce gets used to calculate next velocity, which is then used to translate a rigidbody
Is unityâs standard object pool any good? or is it better to just do it myself?
if this is teleporting it's because you:
- Are using extremely high force numbers
- Are overwriting your velocity in other code.
so you're basically adding a huge force, getting up to a high speed, moving quickly for one frame, then next frame your velocity is being set back to some reasonable number elsewhere
Imo its pretty good and easy to use
it's very flexible, worth using barring a very good reason not to
Hi
Exist a function similar of "KeyDown" in the new input system?
Sure
#đąď¸âinput-system though
Ok
Is there a way to Hide a full class in the inspector without having to put [HideInInspector] in front of all variables?
i rarely have to use HideInInspector because I usually use automatic properties
just make it private
I rarely use;
public int myValue;
in favor of
public int myValue {get; private set; }
HideInspector is generally a bad idea
unless you have a really good reason
because it will be serialized without you realizing it
you want to either:
- make it private
- use [NonSerialized]
Oh okay I see, thanks guys
or use a class that's not serializable in the first place
by default, anything that I set in inspector has either:
[field: SerializeField] public int myVal {get; private set; }
[SerializeField] private int myOtherVal;
Because once I set it, I do not want any other classes to modify it
So I wasn't updating the velocity before changing it, ty for help.
public int myVal {get; private set;} does not get serialized because it is an autoproperty. So it wonât be serialized unless you explicitly ask.
Okay thanks! Makes sense đ
oh, and once you fix these things as we described to be non-serialized, youâll probably see several things in your game suddenly break. This is because they were relying on old values that were saved that should not have been saved. Thatâs okay because those were things that were going to break in the final build anyway.
Suppose isGrounded is serialized when it isnât supposed to be (and you just used HideInInspector). Then I start my game with isGrounded pulling from a saved old value of false. That might not be what it is supposed to have started at.
or youâll find you never initialized isGrounded, and program now complains isGrounded is not initialized. This wasnât happening before because isGrounded was initialized because it was grabbing some old garbage value from a previous session
Need help right now as i just cant figure out why, the problem im having right now is that i just set up my jumping code and if i try it out and i jump and then land on the ground, my canJump variable isnt set to true immideately but takes some time, eventually after pressing space about 20 times again it finnaly set to true again and i can jump
'''cs // Handle jumping
if (canJump)
{
canDoubleJump = false;
}
if (Input.GetKeyDown(KeyCode.Space) && canJump)
{
moveInput.y = jumpPower;
canDoubleJump = true;
}
else if (canDoubleJump && Input.GetKeyDown(KeyCode.Space))
{
moveInput.y = jumpPower;
canDoubleJump = false;
}
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Jump:" + canJump);
Debug.Log("DoubleJump:" + canDoubleJump);
}
CharacterController.Move(moveInput * Time.deltaTime);
'''
i would not make can jump a variable
that should be a function of many other potential things going on
isGrounded, numberOfMidairJumpsLeft, timeLastJumped, touchingLeftWall⌠these should all be variables
i would also include public enum PlayerMoveState { Neutral, Jumping, Sliding, DuckingâŚ}
then CanJump() should give you a result based on those variables
First of all, i have pretty much no idea what an enum is and secon im following a tutorial(udemy course) to learn unity so if possible id like to stay as close to the original as possible
learn enums
they are very useful for states that are mutually exclusive
otherwise you will find yourself with a player script with a bunch of bools, and you will never ever find your way through
second, if you are following a tutorial, and theirâs works, but yourâs doesnât, then you didnât follow closely enough
It probably because im not using the same version of unity as in the tutorial unity 2019 is used
i doubt that
remember your code can be the same, and settings in Unity can be different
Very little (perhaps nothing) has changed between 2019 and now with what you're doing
ill just download the final project and see if i have the same code or not
one simple thing that can mess everything up is just one random setting. one little checkbox
rigidbody simulated off.
collider size = 0;
layer overrides flippedâŚ
It's the same as having the method with braces { }
It's a compiler shortcut that gets applied at compile-time, not at run-time
Thank you
!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.
I have a saving question. I want to make an abstract class (should be singleton), where one method returns a class that is 1) unique to the derived class, 2) is serializable, 3) must be saved in a common serializable save file object. How do I connect the dots?
public abstract TSaveType MakeSaveData();
public abstract void ParseSaveData(TSaveType data);
}```
Letâs say I have a list of these singletons, and each one is ready to have MakeSaveData called, or ParseSaveData called
how do I get all of these into a serializable class, so I donât have to modify my level load, level save, and save file code every time i add a new one of these?
So, I got this problem with my movement/surface alignment.
Whenever my character is walking on a ground that is "diagonal" or something it is supposed to "snap on the ground" so the character has the same angle as the ground.
But in my current script it only sticks to the ground if he is standing still, not when he is walking which I wanna fix.
I tried like 1,000 versions that all went buggy/didn't look well (multiplying Quaternions, multiplying y, x, z or w and much else, it often got worse than now).
I just want my character to stick to the angle of the ground and have a smooth movement on the y-axis.
It looks bad when the character is crouching since it clips through the ground. (screenshot)
Here is the code snippet which is one of those thousand versions I tried: https://gdl.space/boqamikiqo.cs
How can I code my script properly? I don't know if the Quaternion.RotateTowards line is the problem.
i want to end with something like:
[Serializable] public class LevelData {
public List<SerializableInterfaceOrAbstractClass> myList;
}
and I would be able to parse from there
You can try with Quaternion.LookRotation(), the overload with two parameters. Pass the forward direction like you do usually, but also pass the slope's normal direction for the second argument
I'm already using layers for something and now I'd like my prefabs to have a "material " attached to them to determine collision sounds. Is there a standard unity feature for this? Tags seem natural choice but I have a fear of string comparisons for performance reasons.
i would personally just use a component instead of relying on a material
But that would mean on every collision handler, I'd have to do a collider.getcomponent(mymaterialproperties) and I also trained myself to avoid getcomponent at runtime? Is this the famous premature optimization? đ I just wanted to ask if theres an established standard
I was also thinking the rigid bodies physics material? Every body has one and I could use them for this?
(but then again no everything a player or an objects bumps into needs to have a rigidbody)
it's reasonable to use GetComponent in a collision method
you avoid using GetComponent when there's a much better alternative
TryGetComponent is nice for this kind of situation
Can someone help me, i have a game object where i have attached a script that has a "Dontdestroyonload" but for some reason, when i move to the next scene, it's being destroyed :(
is the object actually in the DontDestroyOnLoad scene?
look at the hierarchy
then look at the console
Not really much of an alternative to GetComponent beyond tags
like on the second scene
you are probably getting an error about using DontDestroyOnLoad wrongly
or the code isn't running at all
Would be nice if the unity tag system was more fleshed out
It would be nice if I didn't need an extension method to check a layer against a layer mask đ
How can aou do it like when a player touches the water he will reset to the last spot he left and jumped in the water. So he respawns where he jmped of in the water. Pls ping me thanks
you're the goat for this :)
im finally getting somewhere with the issue i was having after a few days
Store a last land position everytime you jump on your character
okay makes sense. You mesn in the player prefs? Or somewhere else?
I did it but it look quirky now lol
That's the problem I'm always facing when I'm trying to fix this
you can probably do it inside of the playercontroller, have a variable that holds the position and rotation of the player when they press the jump button
okay how do you do that? Lime i dont understand c# that well so. I am using the starter asset first person from the asset store with the script. Thanks for any help
I'm still looking for advice on how to serialize a list of a specific interface
I think i got an idea
When you jump, write:
jumpOriginPos = transform.position;
Save that in a script, NOT player prefs
If you land in water, set position back to that
dm me
Go to chat.openai.com and keep asking it, paste it the whole third person controller script and ask where to add it. It will have infinite patience to answer you đ
Infinite patience and infinite wrong answers
keep asking it if it's sure lmao
"Give me legal cases"
ChatGPT: "Here you go"
"Are these real cases?"
ChatGPT: "Yes"
"Are you sure?"
ChatGPT: "Yes"
=> gets sanctioned for citing non-existent cases in a lawsuit
I work as a software engineer in a different language and field and I don't really need it there, but for my beginner csharp and unity and learning anything at a beginner level it's pretty good.
but, hear me out: it's not
you can't learn from a teacher who knows nothing. that is the blind leading the blind
I've made a custom Matrix data type for a tile system I am working on for a 3D game - currently I can generate a mesh made up of cubes in the Matrix cells that match a predicate, but even after merging vertices there still are way more verts and tris than I would like. How would I go about grouping the cells into the least amount of quads possible like in the this image?
is grey supposed to be solid or empty?
solid
Can you give me an example beginner question it gets wrong? Cause I can probably get you a beginner question it gets right...
this might be naive, but my first thought is to go to every box, and strike out vertices that are already counted
I'm not super familiar with meshes since I work in 2D
A broken clock is right twice a day
The big issue here is that using AI as an answer is ahainst the tules
this sounds like a competitive programming problem
Where do you get these from
Reading
give me a 60 card yugioh deck. ChatGPT gives me a 45 card deck. 10 cards are popular meme cards that are banned. 15 of them are made up cards that simply don't exist
greedy mesh algorithm maybe
Of course if you ask it how to do hello world itll know. If you ask if why your player is jittery or what a good practice is then itll spit out gibberish. It could even give you an answer that you believe is right. One time I tried asking it a math proof and it told me 15 is divisible by 16
cp problem
and if you ask ChatGPT about the made up cards, it will tell you something that sounds like a real card, with the right syntax. but is not legal. does not exist
But the question was how to store a transform position in a variable?
ask chatGPT for help in pokemon. It will recommend pokemon with abilities they do not get, and moves that they do not learn.
And google will get you an answer, probably from Unity forums or Stack Overflow.
And you can trust that answer a bit more than gpt, and verify it by other comments and answers usually, and it isn't immoral to use it
So? You told them to plug in their whole ass script and keep asking lol
with combos that don't make sense
I had a similar thought, taking all interior vertices of the mesh and removing them, but that just caused all top and bottom faces to get deleted leaving me with a border around the irregular shape (the back faces aren't rendering in this image but they're there)
not only messing up the UV maps, but I also might as well just be back at square one since I have no way of calculating the least amount of faces needed to fill in the top portion
alright, I'll check that out. Thank you!
if you are removing all bottom vertices, then your search algorithm is wrong
I don't have a search algorithm, that's what I need help with lol
loop through each coordinate, and check each of 8 verices to see if neighboring spaces are filled or not
I had the exact same problem just looped through the cubes and add to a list of faces if there's not a neighbouring cube. When adding faces just have a dict of vertices to resume them. Kind of brute forced but works
bam. algorithm
foreach coordinate {
if (coordinate is empty) continue;
validVertices = new();
foreach vertex at coordinate {
if ShouldInclude(vertex) validVertices.Add}
FindTris(validVertices)
}
I would hold the vertices on a single spot as a flag enum
So each time I remove a vertex I would regenerate the tris and then move onto the next vertex?
no
Sorry just checked and I ended up duplicating some vertices because I needed different uvs for neighboring faces.
you loop through every filled block
you find the valid vertices on that block.
then make tris based on which vertices (for that block) are valid
it will not be optimized because vertices in multiple tris get counted separately, but unity might be smart enough idk
but it should be the basic idea
How does that group the cells into the largest possible quads?
If I understand you correctly that that would just give each filled cell two tris
oh, you're trying to make big quads
no. each cell can make up to 12 tris
Idsay it's not worth it in your case if this is the scale of your levels unless you want to run on some retro machines.
actually, maybe make a struct for a Quad
This is where I am at right now, I was just hoping to minimize the number of tris
that's an ok start
List<Quad> qList = new();
foreach coordinate {
if (coordinate is empty) continue;
validVertices = new();
foreach vertex at coordinate {
if ShouldInclude(vertex) validVertices.Add}
qList.AddRange(FindQuads(validVertices));
}
then, afterwards, you loop through the list of quads, and simplify
first, quads should have one of 6 orientations (+x, -x, +y...)
and the quad should also store the coordinate for the center of the face
now take your list of quads, and sort/split by orientation
then sort inside based on the orientation
so for all the faces with +x orientation, sort by x. Any sets of +x quads definitely do NOT get combined, right?
so now we take that slice of just quads that have +x orientation, and are all at the same x coordinate.
then we need to do a 2D search in there for quads that are actually contiguous
I'm not sure I understand what the orientations are for, do you mean the quad's normal?
yes
normal stored as an enum
because we don't want to do all this math with continuous vectors when it isn't necessary
two quads with different normals/orientations can never be fused
so for a set of quads in +x, that have the same x coordinate, we iterate through, and depthfirst search or breadth first search to get continuous sets of quads
these are quads that are all connected
do you follow so far?
Yes
ok, now we have individual collections of quads that are connected to each other
so now we're going to go iterate through, and figure out which vertices do not need to exist
or just log the ones that do
ok, next, let's get all the vertices for all the quads in that collection into a list as Vector2Int. Sort by y, then z. Now we're going to look for vertices that have duplicates
if vertex is unique, it is a corner, and must be included.
if we have exactly 4 duplicates of that vertex, then it is interior, and must be removed.
if we have exactly 3 duplicates, then it is an interior corner, and must be included
if we have exactly 2 duplicates, then we need to check if it is a straight line, or a weird connection between two diagonally connected quads
idk this is getting involved, but this is the general idea
I've at least reduced the problem to a 2D problem on a connected collection of quads, which should be way easier to handle
Hey guys so im trying to make a game like kirby strato patrol eos, which looks like this: https://www.youtube.com/watch?v=8NBCl0MqTts. I have 2 problems so far while making this game. 1st problem is the movement as you can see in my video of my game the ai movement is not smooth, they sort of just do what they want they are so suspose to follow the kirbys like in the video. Here is my mouse following script https://hatebin.com/lkedvatnci and my clone follower script: https://hatebin.com/vaehuqrryb The next issue is that when the clone gets hit they should just disappear, but as you can see in the video when they get hit the game ends. The game should only end if the last player/clone gets hit. Here is my code for that in the gamemanager script: https://hatebin.com/lfpbcqhyys and player script, https://hatebin.com/keadfcrbdo. Please let me know if you see any issues! Thank you in advance!
This video shows all bosses in the Strato Patrol EOS sub-game from Kirby Mass Attack for the Nintendo DS. This also includes the final boss and ending.
00:00 Whispy Woods
00:46 Kracko
01:32 Mr. Shine & Mr. Bright
02:09 Meta-Knights
04:25 Meta Knight
05:45 Nightmare
The AI seems correct to me, a bit slow, but seems adjustable.
as for the gameover condition, you should debug your counter to make sure you're appending incrementing values correctly.
c# how to pass an anonymous function as a parameter?
did you try googling this? the answer is just there as the first result
I'm having some trouble with iterating through the directories in the resources folder. I know the folder doesn't exist at run time, but I want to get the file path of each scriptable object I'm loading with the LoadAll. Is there an easy way to do that?
I was hoping to create a dictionary of full file path as the value and the actual object as a key for the sake of serializing the file path in a save and reloading it later
Can anyone help me with making the camera follow a car asset in my game I can't find anything on the topic.
It will be exactly the same as making the camera follow anything, so look up "unity camera follow player" or something. Also recommend looking up cinemachine to make it easier to implement
Ok thanks for the help.
Could probably store the path on the SO itself
or just use Load with a list of paths to iterate over
I watched a couple videos on the topic and installed cinemachine but then when I followed the tutorials like putting the body to 3rd person camera and dragging my car asset into the "follow" nothing happened, the camera just stayed.
Did you drag the car from the hierarchy or the project window(assets)?
Yea
This was an either or question. Yeah to which one?
I dragged my asset from the Hierarchy
Ok, it isn't an asset in the hierarchy, it's an instance. But good.
How about showing some screenshots?
The whole editor with the cinemachine virtual camera selected.
You do have a cinemachine brain on the actual camera object, right?
yea i do
It's difficult to itterate over a list of paths because I can't figure out how to get the list of directories in the resources folder at runtime. I tried the following:
Directory.GetDirectories(Application.dataPath+ "/Resources/", "*", SearchOption.AllDirectories);
When ever I use Directory.GetDirectories(), it does't return any of the folders in resources
Your not cooking rn.
I don't know what that means?
it mean that you are not being useful
Please do not
Ok mb
Wow....
but im mad that nothing is working in unity
<@&502884371011731486> is it cool to tag y'all on this?
Uhhh... Sorry if it's a pain in the ass
@opaque harbor Don't be fucking weird, mind your own business.
Alr
I was going to
I specifically mean to iterate using Resource.Load instead of LoadAll
assuming you've all known paths before loading
I uhhh... don't know all the paths. We aren't keeping the porject organized by asset type, but rather have scriptable objects in many differnt folders based on what scenes they are used in
Plus... we have stuff get moved around and reorganized and if I manually set a property that tracks the file path on each scriptable object, it's gonna be a pain to find if we move something
then storing the path in the object itself could be the idea. Iterate over the list of objects from LoadAll, if it's a type of SO then read defined path and store in specific dict.
OnValidate to set path
Use GUID instead, it won't matter if they move the files as long as you keep the GUID https://docs.unity3d.com/ScriptReference/AssetDatabase.GUIDToAssetPath.html
Yeah, AssetID is ideal
note it's custom editor stuff
Oh cool! Thanks
I'll try this
Also, this, if it doesn't work
// Get the asset path of the Scriptable Object
string assetPath = AssetDatabase.GetAssetPath(this);
// Get the GUID of the asset and set it
storable_ID = AssetDatabase.AssetPathToGUID(assetPath);```
Oh sick! Did exactly what I needed
Thanks so much y'all
Oh wait... Does this only work in the Editor? I think I skipped over the asset data base class doing research cause of that, but I guess I was mistaken?
GUIDToAsset is editor only, I was suggesting instead of using paths just use the GUID provided by unity
meaning you'd instead serialize by the GUID instead of the path
void SpawnUnit()
{
nextSpawn = Time.time + spawnDelaySeconds;
Vector3 playerPos = Player.Instance.transform.position;
float xOff = Random.Range(0f, 360f);
float yOff = Random.Range(0f, 360f);
Vector2 directionToSpawn = new Vector2(xOff, yOff);
directionToSpawn.Normalize();
float distanceAwayToSpawn = Random.Range(20f,30f);
directionToSpawn *= distanceAwayToSpawn;
Vector3 spawnPos = new Vector3(playerPos.x+ directionToSpawn.x, playerPos.y, playerPos.z+ directionToSpawn.y);
Instantiate(EnemyPrefab,spawnPos, Quaternion.identity);
}```
is this a good way to go about spawning an enemy in a range specifically 20-30 units around the player?
add the minimum to xOff and yOff otherwise looks good
or rather I'm not understanding those offsets that you then clamp it with another value
are x and y off supposed to be in degrees?
OH oh actually i just realized yeah, the idea was basically making a random vector to deside the direction they were spawning in, then picking the lenth of that vector but i just realized a better way to do it
void SpawnUnit()
{
nextSpawn = Time.time + spawnDelaySeconds;
Vector3 playerPos = Player.Instance.transform.position;
float xOff = Random.Range(0f, 10f)+20;
float zOff = Random.Range(0f, 10f)+20;
Vector3 spawnPos = new Vector3(playerPos.x+xOff, playerPos.y, playerPos.z+ zOff);
Instantiate(EnemyPrefab,spawnPos, Quaternion.identity);
}```
i had that before but i was having trouble figuring out how give it a minimum range and i just realized i can just lower the random range and add the minimum to the offsets
oh it's 3D now im confused haha
but basically if you're in the middle and you want stuff to spawn around you by position, then you also have negative values if your character is the pivot
i was about to say yeah how can i do negatives...
If you want the values to be even around a circle, I recomend randomizing the angle and distance
basically im making vampire survivor but 3d so i want to spawn enemies all around the player
circle is actually easier now that I think about it
yeah how do i do that tho? like make a vector with a random angle
random direction + distance
thats basically what i thought i was doing in the first snippit i sent
UnityEngine.Random.insideUnitCircle
Oh thats a thing?
if you want any direction from the player (including up/down) you can use https://docs.unity3d.com/ScriptReference/Random-onUnitSphere.html
otherwise just use https://docs.unity3d.com/ScriptReference/Random-insideUnitCircle.html then create a Vector3 from that and slap the Y axis into the Z axis of your Vector3 and normalize it
Then you make sure the y is equal to the Y of the ground at that point
yeah the ground is flat atm so i just have it set to player hight as a place holder
Cool
yeah, doing direct position around requires a bit more conditional logic
Random.insideUnitCircle helps tho
I think I've tried something like that previously
alternatively, if you do change the height to vary, you could raycast from (x,arbitrarilly high,z) straight down and get the y of the terrain of on the hit
just a thought
void SpawnUnit()
{
nextSpawn = Time.time + spawnDelaySeconds;
Vector3 playerPos = Player.Instance.transform.position;
//Make vector with random angle
Vector2 directionToSpawn = Random.insideUnitCircle;
directionToSpawn.Normalize();
//Pick distance
float distanceAwayToSpawn = Random.Range(20f, 30f);
directionToSpawn *= distanceAwayToSpawn;
//Spawn Enemy
Vector3 spawnPos = new Vector3(playerPos.x + directionToSpawn.x, playerPos.y, playerPos.z + directionToSpawn.y);
Instantiate(EnemyPrefab, spawnPos, Quaternion.identity);
}```
Don't need to normalize it
i just checked and that does not appear to be the case, it gets a random point within a unit circle not only along its edge
were here to learn are we not? đ
indeed!
To clarify, ONUnitCircle is a vector of 1, just not in
https://math.stackexchange.com/questions/3810318/parametric-functions-to-make-sine-curve-follow-a-semicircle-of-radius-1-5
I implemented something like this similar to create some patterns to some waves
vampires has some more detailed spawns beyond just random sampling
I saw on unit sphere, but no on circle?
insideUnitCircle needs to be normalized because it can be anywhere within the circle. onUnitSphere does not because it gets a point on the edge of the sphere so it is already normalized
sadly there is no onUnitCircle, but just normalizing the result of insideUnitCircle would be the same
unless it's (0,0), which is a one in a million error, lol
or... more than that, but still
yeah it is very unlikely to get 0,0 since it just uses Random.value for each of the axes
though it is technically possible
just add 0.001 to the values
I have a habit of just adding some extra offset values to stuff like directions just to make sure it never zeros out ;)
Sorry yeah, just mis"spoke". That one
It would make sense though
does normalizing a 00 vector error or just return a 00 vector?
returns 0,0
oh kk so i can just check for that cool
https://docs.unity3d.com/ScriptReference/Vector2.Normalize.html
If this vector is too small to be normalized it will be set to zero.
don't crosspost
How to make the volume louder? I already have the volume to its max, 1, but I still don't think its loud enough.
this is a code channel. try #đâaudio
At a certain point, the audio file itself just needs to be louder before putting it in Unity
But yeah #đâaudio
Hi again i have a few problem with my tilesmap I don't know if anyone did this but i need to retrieve the tiles that has collider or not is it possible ?
the water are my colliders
i have two different tilemap the green one is a walkable one the water is nonwalkable and have a tilemapcollider2d
guys I needed to make a datamanager script for the game and asked chatgpt to generate it , it made me playerprefs script but after asking for secure method I gave me binary method something, and saved the file as data.dat
is it ok to save the progress and resources of player in a strategy game?
- don't trust chatgpt to give you good code
- if it is using binary formatter then don't use it, it is a potential malware risk for your players
https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
i think their question was more along the lines of "is this a good method of saving progress"
Oh! Is BINARY ok for it
Ok, that makes more sense haha.
Yeah, that is a good method. Lots of games use Binary for it. It is a slight obfuscation to the save data. You can still modify it with tools, but it's not as dead simple to change as JSON, in case you care
Hey y'all. My project isn't building because I was usinbg stuff from the unity editor namespace, but I've cut it down to just the OnValidate method of my Scriptable Objects. Is that still a no go?
All editor code needs to be in an Editor folder or use preprocessor directives (the #if UNITY_EDITOR lines)
It must be like that to be discluded by the build
Thanks
Welp, I guess all the SO assets are going into the resources folder after all lol
Which one to use then?
Don't use a chat bot to code for you
Use it to explain concepts and keep asking it until it explains them in terms you understand
//storing rotation in a vector2
private Vector2 currentOrbit = Vector2.zero;
private Vector2 destination;
void Update() {
//getting the directional vector
Vector2 path = currentOrbit - destination;
path.Normalize();
//using directional vector to get to the destination
currentOrbit -= path * speed * Time.deltaTime;
//Clamping values
currentOrbit.x = Mathf.Clamp(currentOrbit.x, minVerticalAngle, maxVerticalAngle); //clamp orbit angles
if (currentOrbit.y < 0f) { //maintain that rotation stays between 0-360
currentOrbit.y += 360f;
} else if (currentOrbit.y >= 360f) {
currentOrbit.y -= 360f;
}
//using currentOrbit to set rotation and location
Quaternion lookRotation = Quaternion.Euler(currentOrbit);
Vector3 lookDirection = lookRotation * Vector3.forward;
Vector3 lookPosition = target.position - lookDirection * distance; //distance between camera and point
transform.SetPositionAndRotation(lookPosition, lookRotation);
}
Hey people, so in the code included I am trying to move my gameobject around a sphere.
This is working so far as I can get the directional vector between my current orbit and destination and adding that vector to my current orbit
Now the problem comes when I am trying to move across the 0-360 line, instead the path is wrapping around the long way to get there
here is a (ok) diagram to explain
now the path is just a directional vector to clarify
so maybe that term is misleading
the red line is the 0/360 angle
on the y axis
if (currentOrbit.y < 0f) { //maintain that rotation stays between 0-360
currentOrbit.y += 360f;
}
```eg if destination rotation is 350 and current is 10, you want rotation of -20 degree on x-z plane, but you clamp the angle so the rotation is 340 degree now
yup
Here's a different diagram to explain
note blue is still current orbit and both green dots are the same destination
to restate, moving within the black box (representing the vector2 of the sphere, the sphere unwrapped flat) is perfectly fine its just when going through the 0-360 line, it takes the long way to get there
please tell me if im not making sense or for any clarification
i know, that is the reuslt, you restrict the angle range from 0 to 360 but it should be -180 to 180 instead
So, I would want to make the coordinates relative to the current orbit?
like this?
i didnt say anything on the reference frame
imagine your clock, what is the fastest way (or angle) to rotate a hour hand to 12 if it currently is pointing to 3, assume clockwise direction is positive
it would be the negative angle in that case
yes
so you know why the range of rotation is -180 to 180 now?
what ever you start count the clock starting angle from 12 1 2 3.... , the rotation angle is always -90deg
hey there, can someone point me into the right direction? Im trying to make simple game in wich i need enemies to wonder around and sometimes attack each other or player. By attack i mean throw player into spikes. How can I make enemy like calculate the right angle to push player into his death?
you'll want to start at a step of the time and first figure out your method of AI and pathfinding
crossposting or asking people from other channels for help is not warranted . . .
nobody is answering me đŚ
it may take more than 5 minutes for someone to respond. people will help and answer if they know how. also, it's before dawn for most of the active users on a weekend; not the best time . . .
i have a problem, but first, an example..
an object can have a layer, selected from a list of layers. only one! not several!
a layermask however, can have several layers, selected from a list of layers
im trying to make this sort of thing, but with enums.
i have a AI_Factions enum, that is a multi choice enum:
[System.Flags]
public enum AI_Factions
{
Resistance = 0,
Combine = 1,
Monsters = 2,
NoTarget = 4,
}
now, i want the class, AI_Target to have this enum, but be able to only select one option from it, just like how you can only select one layer for a game object, orrrr, like a normal enum that isnt multi choice
but i want another class, AI_TargetingSystem to have this enum and be multi choice, just like layer masks or a normal multi choice enum
so how can i make this enum be multi choice in one script, but single choice in another?
hard to chop up the constraints like if you're passing these enums in a namespace other than the scripts themselves
so the answer is either use two different enums, or just stick to the multi and not set multiple types
what i want to do is check if the faction, set in my ai target script, is included in a "faction mask"(like a layermask) that is set in my targeting system. so what you are telling me
is that i need TWO enums, one is single choice, the other is multi choice, then use a switch statement to see if it is included?
beacuse with one enum i could just use .containsFlag
you could have this faction data live inside a SO or a separate script, and there you can enforce any rules about what a characters faction can be. I use SO and just create 1 per faction, but i also have extra info like what factions they are friendly or aggressive towards
thanks đ
i dont think you even need to use flags here tbh
AI_TargetingSystem to have this enum and be multi choice
you could also just have a list of the enum
not as efficient but đ¤ˇââď¸ saves you this hassle of trying to enforce this sometimes single, sometimes multi select enum
problem with list of enums is that you can select multiples of the same enum
but it's another thing where you can just "not" set it
ill just add several bools. this isn't worth the trouble
really, most of these problems are more editor related than code
which can be fixed via custom editor or on validate
I sorta want a translucent object, which channel would be best for that?
if you're making #archived-shaders otherwise #đťâunity-talk for more mesh/unity related component questions
i think out of all the options, adding several bools is probably the most tedious solution since whatever this is checking might cause issues down the line.
Really the solution is either just dont set multiple values (you could use some OnValidate thing to ensure only 1 is checked)
or
do what i said with a list and keep in mind what Mao said about not selecting multiple of the same enum. This wouldnt even be an issue realistically as it would just run a check against 1 extra entry
what's wrong with just checking if the flag is in the (bit)mask? that's a simple check . . .
how do i do that?
bitwise and
how do i rotate an Image in a canvas with code?
i tried to make the scale negativebut the image just show nothing when i do that
sorry, as @fervent furnace mentioned, use the bitwise & (and) operator with both layer masks and check if not 0 . . .
don't crosspost . . .
i meant posting in multiple channels. it's fine to keep the original post in #đťâcode-beginner
ye i know
nah, it's almost 5 am; i work at 8 am. need sleep . . . đŤ
okay no problem
why cant i just say "E" anymore?
what E, is it even related to unity
you can't say individual letters because of the rule that you say things in sentences or something that resembles them
"Please use complete sentences with full context. You can also edit your previous messages."
k thanks (tbh i meant to say it in another server)
is there a way i can make the transition duration from the idle state to the run state cancel if my shoot state gets triggered???? it looks really weird because my shoot animation only plays after the transition duration finishes so it looks really messed up... ive been trying to fix this all day by just making it so you cant shoot for a second after you start sprinting but it never worked
baffled by this issue... why isn't it 0.5 ?
ofc integer division
I don't understand, it's 0 because I'm passing integers ?
i guess it rounds it down ?
if positive=>floor
if negative=>ceil
đ¤ interesting
not always round down, btw beginner stuff
If the result is a decimal, a int cannot hold that value, so int divided by int will result in a int rounded, and the result will always be the type of the denominator, so int divded by float can return a float, int divided by long can return a long, etc
not the type of denominator
int/float or float/int return float because int is casted to float
Oh really? I remember doing some type-math outside of Unity before, and wouldnt always get consistent results unless the denominator was cast to the type I wanted, didnt know you could also cast the numerator for the same result
- If i have an editor-only methods for monobehaviour (related to validating components presence as an example) that are both placed in the preprocessor directive and given a conditional attribute, will the project build without failing and without compiling either the methods nor the calls to them?
I used the input field for this kind of chat, but when i build to android and use google play pc emulator for testing keyboard, i can not use Enter key to execute the ok button, anyone know the piece of code, reference?
Nothing inside an #if UNITY_EDITOR will exist at all in the build
Any references to the class and/or its methods that aren't guarded by a preprocessor directive will fail to compile
this makes the conditional attribute a bit pointless, since any attempt to call the method in a build will produce an error anyway
What you can try to do if it's used everywhere is make the class partial and declare the methods without a body, so when it compiles it just compiles the partial class that's empty
- At the same time, the conditional attribute should cut out all the invokations of the said method. Or am i wrong here?
The method doesn't exist at all
neither does the conditional attribute
it's all gone
Yes provided that you put it everywhere
#if UNITY_EDITOR
[Conditional("UNITY_EDITOR")]
public void Foo() { }
#endif
If UNITY_EDITOR is not defined and I try to call Foo(), none of that code exists at all
Assuming "attribute" as the #if preprocessor directive instead of a C# attribute like [SerializeField]
Who uses that lol
it tells the compiler to ignore method calls
I think the idea is to prevent major parts of your program from appearing and disappearing depending on build settings
it doesn't matter that you put a Conditional attribute on Foo. Foo doesn't exist at all.
Neither does the Conditional attribute.
- I see. Exactly what i was not certain about. Damn, it'd be so cool to have a way not to exclude methods automatically, without keeping in mind that every single call has to be wrapped in the directive, but sigh
you could put the entire body in an #if directive and then make the method conditional, I guess
or just make it conditional
this would be an extremely marginal improvement (you wouldn't need to include the ignored method's body in the build)
- That's what i'll do, yes. I'm just that kind of micro optimization idealist who searches for a way to shorten the app size by those pesky 12 bytes every time đ
I have messed with every setting under the sun and my GithubAction using Game-CI will just always take 1000s to render out these 432 variants
I have a function named IsGrounded(), when I call it, it returns true or false.
Is it possible to call this function in a if-statement?
I tried this but it didn't work:
if (IsGrounded())
{
// code
}
that is ok, syntax
But I get the error
Cannot implicitly convert type 'void' to 'bool'
then IsGrounded does not return bool
I'd like to ask a question about assemblies. If I understand correctly, if I make an assembly, Unity auto-adds every .cs in that folder to the assembly. Then unity compiles these assemblies, and if file1 depends on file2, then... how do I make it depend correctly
also, can I add a file from one folder to an assembly in a different folder?
I'm just trying to figure out how to add assemblies without breaking everything, as I learn this tool
when using GetComponentInChildren, it will loop in all direct childs until it founds the component or null if all childs were scanned ?
GetComponentInChildren checks self, then children, then children's children, then so on. Looking for the component
okay ty
remember it WILL check self! very important
regarding your question about dependencies
lets says you have a folder Player, with your script(s), and a AD
and a folder game elements with your script(s), and a AD
if inside a script in Player you want something that was (for i.e) declared in game elements, Unity will not find it and you will get a error in VS (like "class not found"), you will have to add in your Player AD a dependency to game elements AD
to start with, you are not talking about assemblies here but asm defs. An assembly is a .dll file (which can also be made outside of unity) an asm def is an assembly definition which will result in a .dll when compiled
this happrens sometimes to me when wanting to use TMP or cinemachine, i have to add it in my AD
ok, so let's say I am adding assemblies now to my project, and I have a rough idea of like a graph in my head of how the dependencies go
I have some files just in the standard C# assembly, but they depend on something that is now in a different assembly. How do I get around this?
usually by using namespaces, all asm def.s have Assembly-CSharp as a dependency
generally I just cut out the crap middle man and make .dlls outside of Unity and add them to a plugins folder
I'm just trying to link things in a non stupid way right now, without breaking all of my code, as I have not been using namespaces, but I want to start bringing things in
and it will be very hard for me to add this if I can't know if something works until after I go through a giant project
namespaces are a must when splitting code over multiple .dlls
I have a class that has method which starts a co routine. If I instantiate that class, save it to a private variable, execute the method that starts co routine. Then assign the variable that hold that instance to null, will the co routine continue till finished or will GC flush it down the drain?
if you want to test stuff and have all the code for an assembly inside one folder just make a dll project in VS, add the code to it and the correct Unity references and see if it builds
The coroutine is tied to the MonoBehaviour that StartCoroutine was called on. Nothing else matters
I'm just confused right now because I have all these files in folders that are not split up by dependencies
Thx
well, that is your first job
I split them up in a different way. is there maybe a plugin to make custom DLLs easily?
no plugin required, it is standard VS
how about to find how my classes depend on each other, so I can more quickly see how I might want to split DLLs
you wrote the code, you should know that already
I am making a 2d hex mesh grid.
How do i layer my mesh ontop one another?
For example, when highlighting, I will simply add a highlight mesh ontop of the base mesh, and increase is y offset.
Is there a better way to go about this?
so.... is the first order of business to put everything into namespaces by the DLL I want them to be in?
or is there a way to do this without starting with all the namespaces
yes and by putting them into namespaces this will highlight the dependencies
this is why we design code before writing it, so we dont get this kind of shit
I didn't fully understand making my own namespaces before hand. Never worked on a project so big before
Unity developer moment
In regular C# app you get 1 namespace per physical folder, along with the root namespace named the same as your project
Does someone know a better way I could retain the momentum of the player between walking jumping state. I am using a state machine for player movement. I coded the jumping state so that the player stops moving in the air when the horizontal axis is 0. But doing this stops the player when they jump already moving. I coded it so that if the player is moving it wont allow change in direction until one of the Horizontal buttons are pressed but that has problems as if the player presses the same direction they are moving in they just stop.
https://hatebin.com/vdgiqqqgwo
what? you can have as many namespaces as you want
I didn't say otherwise
I just said that, in apps out of Unity, namespaces will be pre-generated according to the folder structure
Whereas in Unity by default it just crams it all into the global namespace
So it's just funny that C# devs that only used Unity have never been introduced to namespaces as soon as "others"
and yet they use namespaces all the time in using statements, meaning that they didn't learn very well
hello guys do somone have time to help me with simple script? its gonna take max 5-10 min if u are not begginer like me
not the way this server works, post your code in #đťâcode-beginner with all relevant information
how do you check if the information in an object of type Type is valid or not?
eg points to an actual type
Not null?
You can use is and pattern matching
won't that return an error?
No
you can use if ... is type or object as. object as will return null if the cast is invalid. the is construction is more efficient
check if it's null
I don't think you can construct a bogus Type object
is would be relevant if you were checking if an object is a certain type. that's not what is going on here
Hi, so I made it so that the player has a 'do not destroy on load' enabled and that works fine however I have an issue with UI image for the health bar which I tried slapping 'do not destroy on load' but it didn't seem to like it, not sure how else I could do it other than have the health bar images be inserted into the player rather then on the canvas which might have it's own issues
what do you mean "doesn't seem to like it"
do you mean you got an error because you didn't call it on a root game object?
I'll show the error, I think I can see the issue just unsure how to change to to allow more than 1
maybe remove 'more than one'
You wonât be modifying the visual scripting code
Sounds like youâre not supposed to mess with the object thatâs holding the VS variables. Not sure how youâve got this set up..
hmmm I see, well thanks anyway it just means I have to push it aside for now
Need some help with figuring out the problem.
This is my walljump code:
private void WallJump(RaycastHit2D rightRaycast, RaycastHit2D leftRaycast)
{
// Calculate wall jump direction
float wallJumpDirection = 0;
if (rightRaycast.collider != null)
{
wallJumpDirection = -1f;
}
else if (leftRaycast.collider != null)
{
wallJumpDirection = 1f;
}
// Reset velocity
rb.velocity = new Vector2(0f, 0f);
// Apply wall jump force
rb.AddForce(new Vector2(wallJumpHorizontalForce * wallJumpDirection, wallJumpForce), ForceMode2D.Impulse);
isJumping = true;
isWallJumping = true;
}
I have confirmed that the raycasts passed are correctly set, as such, the walljumpdirection is also set properly. In this case its -1
I reset the velocity of the player to 0 on both axis, then add a force up and to the direction the fall is facing.
For some reason even though the walljump is detected, and the force gets applied, it is doing so inconsistently and I don't know why
I have such a problem, created a territory unity 3d, but when I want to add more height, nothing comes out and it does not change (Same problem with downsizing)
maybe the problem is with the force you're setting
you want it to push the ball away from the wall
or else it either makes you be able to wall jump infinitely
or bugs out
also, define weird movement
it being moved away from the wall is weird?
I made this simple auto tiling script and I wonder can I somehow do that these values could update in editor instead when game starts?
lets say I have an instance of MyClass?, and I want to make an extension of it where, if the instance is null, we get a specific result. eg : public static bool IsValid(this MyClass? inst). How do I make this work?
So when I change scale of the transform in editor it would show me how textures look before I played game
is there a way to make a corutine run in paralell with fixed update? like would this work?
IEnumerator SeekPlayer()
{
while (true)
{
yield return new WaitForFixedUpdate();
}
}```
that would make it yield until a FixedUpdate frame, so yes it will run in time with FixedUpdate. do note that it will finish yielding after FixedUpdate has run that frame though
I attached a video. You can see it looks nothing like a jump. It just kinda moves left and falls immediately.
is that not what I'm doing here though?
rb.AddForce(new Vector2(wallJumpHorizontalForce * wallJumpDirection, wallJumpForce), ForceMode2D.Impulse);
I'm pushing the player to the side and also up
so it should act like a diagnol jump but its not
and it doesn't always do this. That's what is bugging me the most
is there a way for me to automatically try to make assemblies that obey namespaces?
like, I now have several classes and files where basically everything in the file is in a given namespace. is there a simple way to⌠put them together in a .dll by namespace, and let the computer try to figure out dependencies in a way that is not shit?
also, is an assembly a function of the class or the file?
sort of the file, i guess. in a normal project your different projects are each their own assembly. in unity you can use assembly definitions to break your code up into multiple assemblies
I see. but asmdef are all immediately a function of the folder, correct?
well yes, but if you have classes that should be in separate assemblies why would they be in the same exact folder?
i have more of the opposie problem, of files that I want in one assembly in separate folders
Hey guys
Short question: How do I detect whether if an scene has been loaded because the application started or because another scene loaded it?
Long question: I have opening and closing animations for scene transitions. The main scene is the Main Menu, which is the first scene to be loaded when the game starts, but you can also reach it by returning from the game. In order for animations to work properly I need to check if the Main Menu scene was loaded because the application started or if it was loaded by returning from the game scene
you can use a singleton that is don't destroy on load to be notified of whatever happens
or just a static variable that is only changed after the first time the scene is loaded
yeah, i was thinking about a dirty solution like that
is that really a dirty solution though? đ¤
a more elegant solution would be if unity had a tool that can check it for u
anyways, there is no need of a headache for something that simple lmao
but that is also static . . .
xD
but it feels better
i already have a "GameInfo" static class so i'll use that
why though? a single bool being static and kept in memory versus an entire object kept in memory for the duration of the game
it's a lot easier to manage a single singleton class implementation, which manages its own private static instance
maybe static is just the way to do it, tbh. use it or lose it
realistically, you probably do want a singleton, because you will probably keep more than one bool. A singleton could help manage general interscene data transfer.
because later it'll grow from a bool, to a bool, an enum, a list, another enum, and 5 more bools
private static bool hasLoaded;
private void Awake()
{
if(!hasLoaded)
{
DoInitialLoadStuff();
hasLoaded = true;
}
}
is literally all that is needed
I have a static class with public static variables in it. Pretty useful I can access and modify any variable from any scene
static bool is definitely just fine here, singleton doesnt make sense here unless you actually need an instance. At that point you might be doing too much with one script. Any other "clean" solution is just going to be unnecessary for the sake of feeling like you're doing it properly
remember the KISS principle
Also remember to selectively apply DWW and WGAS, two terms I just made up
(do what works, and who gives a shit)
I have a Singelton<T> : MonoBehaviour class that I downloaded, so all I need to do to make a block of code a singleton is make it: public class MyClass : Singleton<MyClass>
yeah I know, I also like doing stuff properly, but when you are one week before launching your game... anything works
I downloaded my singleton implementation lol
đ¤Śââď¸ WGAS is deprecated
do you even GLRT
good luck, really terrible
sometimes i look at blog posts about OOP jargon
and I wonder if these people ever actually write code
yeah, the "is this aggregation, composition, or neither" question yesterday really did me a number
every time I add an asmdef to my unity project, the scripts in that folder can no longer find things from the rest of my project. How do I allow code from one assembly to access the main C# assembly? or is that not correct?
access doesn't flow that way
i figured I was doing it backwards somehow
that's what i was thinking of, lol
Could you just throw an asmdef into the Assets folder to put everything into a "default" assembly?
I haven't thought about how that'd behave
Yes, as long as you handle all the Editor folders
I keep looking at that page, but I don't understand the flow, since I have many files outside of assemblies, and in the default assembly
ah, good point
those suddenly don't work anymore
The "default assembly" is Assembly-CSharp
(and no file can be "outside" of an assembly)
the scripts merely aren't covered by an asmdef
yeah, but that means they are in the default C# assembly
you can imagine there's an asmdef in the root of your project that slurps everything into Assembly-CSharp
(except for Editor folders, as vertx mentioned)
(which are Assembly-CSharp-Editor)
this reminds me of something, actually
Several parts of my codebase could currently be put into an assembly very easily
like my settings system, which doesn't care about anything else in the project
No time to write code when you need to draw stick figures, circles, squares, and say that this is proper [Acroynm] structure
...actually, nevermind, just answered my own question lol
I can just asmdef the "core" of that system and then extend it outside of the assembly if I want something to be able to see the rest of the project
just like how you'd extend a third party library by creating scripts that aren't in its assembly, assuming you don't need internal access
ok, so let's say I have: Class1.cs (everything in project needs), Class2.cs (needs Class1), Class3.cs (needs Class2)... How do I set this up? does my folder structure need to match this?
folder structure is important, but you can override it by placing asmdef and asmref assets in the folders
Assembly Definition Reference assets let you include another folder in an existing assembly
folders only matter if there's assembly defs in them controlling the assemblies
sorry, I've just never worked with assemblies before
an actual example might be more useful
suppose you have 100 scripts that implement some self-contained feature
like a graph library. it has classes for nodes and edges and lots of graph algorithms
it doesn't need to see the rest of your project. it can stand entirely on its own
this is a good candidate for an assembly definition
you'd put all of those scripts into a folder (or into a subfolder) and stick an asmdef asset in it
so... do I start by putting one asmdef at the root of my project, which would then include everything, then give subfolders their own asmdefs?
hang on, finish this example first
does it make sense to you?
The motivation here is that you no longer need to recompile that giant pile of scripts every time you make a change to your game
ok, so an assembly should be self-contained
In this simple case, yes.
it's the most obvious way to use 'em
Now suppose you've got a second library. It depends on the graph library.
But it's otherwise self-contained.
You could shove it into the graph library's assembly
Or you could make a second assembly definition for the second library.
When you do this, you will get a truckload of errors.
The second assembly cannot see the graph assembly.
That's where these references come in.
so the second needs to ref the first?
You can reference the graph assembly from the second assembly.
Exactly.
These references must be explicit because...
"auto referenced" applies just to the pre-defined assemblies
Manually defined assemblies only see things in their list of references
So Assembly-CSharp.dll automatically sees both of these assemblies, unless you untick that box
The assemblies form a directed graph.
critically, you can't have cycles in this graph
if A references B, B can't reference A.
because how would you compile them? they need each other
i got that. I just don't know how to split
okay, good
so, coming back to this
you usually make the "main" assembly -- the default Assembly-CSharp.dll one -- reference all of your other assemblies
(that's what auto-referencing does)
so let's say I have 100 scripts all in one default asembly. I now identify a group of 10 scripts that depend on each other, depend on the other 90, but none of the other 90 depend on them
how do I split this off (so I can slowly make my way to splitting everything)
The other 90 would need to be placed in folders with either an Assembly Definition asset (which actually...defines the assembly) or Assembly Definition Reference assets (which include more folders in the same assembly).
the 10 scripts would remain in the default assembly
so for this, can I put one asmdef in the root folder that contains all 100, then put another asmdef in a subfolder with those 10 which I identified
and then slowly work my way back
i just need to break up this problem into smaller problems that I can chip at until it' s all done
but if I don't take the first step, I'll never make any progress
I have my scripts set up like:
Scripts
âââ Editor
â âââ MyEditorExample.asmdef
â âââ EditorScriptExample.cs
âââ Runtime
âââ MyRuntimeExample.asmdef
âââ RuntimeScriptExample.cs
and I think that makes sense
and then any rando asset store assets:
External
âââ AssetStoreAsset
âââ AssetStoreAsset.asmdef
âââ Editor
âââ AssetStoreAssetEditor.asmdef
Yeah, I've started doing that with large packages that wound up in Assets
but then how does runtime code see AssetStore code
it references it in the asmdef
yum
also note that the "Editor" asmdefs need to be set so they don't get included in non-editor platforms
Hey, I'm having some trouble when working with a dinamically made Texture2D in my project.
Context: I'm working on an asset with my mate @tranquil canopy. We use this method in order to generate a blur texture, and then apply it to a button in one of our custom editors... But only my teammate sees the button with its correct texture... Not me or any user who downloads the asset.
private static Texture2D MakeText(int width, int height)
{
Color[] pix = new Color[width * height];
Texture2D result = new Texture2D(width, height);
result.SetPixels(pix);
result.Apply();
return result;
}```
Here goes the crazy thing: If my partner uses a white texture (``Texture.white``) instead of the method I've shown, he still **does** see the button with the correct texture... What might be wrong with his Unity project?
This is how I and other users see the buttons:
And @tranquil canopy can you show how the buttons should be seen? (How you see them)
I just put one .asmdef in my main root assets folder. I now got this error:
error CS0006: Metadata file 'Assets/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll' could not be found```
How would I resolve this sort of error?
I do have the .dlls, and can find them in a subfolder covered by the asmdef
that method generates a transparent texture
That's what it should generate, so that the editor can use it as a "color modifier"
Doesn't it work like that...?
folders don't matter with DLLs. Reference them via the assembly definition
you've not described what you're doing apart from "generating a blur texture"; and that texture is just a transparent texture
you mean my asmdef should reference the dotween dll?
Yes
If Override References is unticked, then it should already be referenced. If it's ticked then you need to reference it manually
This is more about editor extensions... But those are the only times we use the method
Then that style is passed to GUI buttons as a parameter
well, you generate a 2x2 transparent texture and assign it to a button, so it should just hide the button
But it doesn't for @tranquil canopy, for any reason
yeah... i see this with the same unity version and the same unity proyect...
and the same code...
can't you just set the background to null? Why even generate a texture?
There's no modding discussion on this server (see #đâcode-of-conduct )
ah my bad
just cause it looks quite better with texture...
We mean, this is the difference:
(It looks kinda more elegant, and that's the window esthetic we're looking for)
it still can't find it. Folder structure looks like: (Folder with PluginsExternal)/(Folder with Dotween.dll)/(Folder with DotweenEditor.dll)
without even splitting them up, I'm just trying to see if I can get them to see each other
Again, the folder structure does not matter for DLLs. They are precompiled.
The references are set up correctly in that asmdef. If you're still having weird compilation problems, restart the editor. Fiddling with precompiled DLLs often will require a restart
ok. I thought I was still doing something wrong. crtical step
Sorry, I use UITK only for several years to avoid this nonsense.
I would personally pass it a label style instead of a button style so most of this stuff is preconfigured; then you'll probably just have to center the text
EditorStyles has a bunch of stuff
ok, now none of my scripts can see anything covered by anything in the plugin assembly, which I think is correct?
because my plugin folder with asmdef is a subfolder of an asmdef with everything
so if I understand correctly, I need to get that into a separate folder, so my own scripts can have an asmdef that depends on external asmdef
then unity will automatically make the assembly for external, make assembly for my scripts, and make my scripts depend on the external. right?
Thank you, I'll tell my friend and we'll consider that possibility :)
How can I "unlink" child rotation from parent rotation? I need a gameObject to follow another one so I made it its child, but I dont want the child object to rotate with the parent object, can I achieve this?
don't make it a child. use a position constraint to make it follow the object instead
idk everything in my project is just totally broken now. I need to step away from this
ok thanks
Where should default values for a game be stored and loaded from? For example, if I have a class handling the picking up of objects and want to play a pickup sound that will be the same for all of these objects, then where should this class look for its sound? My first idea was to serialize the audio clip, but then I would need to manually set all clips in all pickable objects. Then I thought of creating a 'DefaultValues' MonoBehaviour with a static instance that would store all 'default' values, but I'm not sure if that's the right way.
Well I made a static class and put a lot of public info on it, but it depends on what you want to achieve, maybe for you it is better to use unity events and handle everything inside an Audio Manager gameobject
might also do it with a static class
if your class manages picking up, you can put the audio file there and just play it for every item you pick, no need to put the audio on every item
i meant a script that is attached to pickable objects
and what if you have a prefab of a pickable object and just use OOP to customize them?
also I'm not sure if setting everything to public is a good idea, I propose using private but serialized fields to avoid changing the default values during runtime
then it would still look for the pick up sound in the static class since all sounds should be the same
no one changes variable values but you, I think encapsulation principle is useful... when no one whatches. If your code is well implemented there shouldn't be errors related with that
just put the audio file in the prefab. Prefabs can have default values from project
right
and your right about encapsulation, but it helps me organize the code and when I comeback to it after sometime it's easier to understand
how can i make it so when a object is childed in code the object scale doesn't change
You should be able to set a default value in the inspector, by clicking on the script in the project files
Do you need the object to be a child even? You could just have it follow the parent
i do
because i want it to also move with rotation
Then have it rotate with the parent instead via script, itll be better than constantly trying to undo a scale change
but do you know a way to make the scale not change
No, this is how parent-child objects function. If you dont want it changing along with the parent transform, you dont need it as a child
alright
im trying to make a vampire survivors like game but as an fps and I'm not sure how to go about replicating the endless map, the player should intheory be able to hold w for hours and never reach an edge
should i implement it like procedural generation? creating new level chunks once a player nears an edge?
Well endless is gonna have to be procedural in some sense, but you'll have to keep the player at the world center and move the world instead. If you go very far, things will start breaking with floats
As opposed to doing a crap ton of chunks by hand and looping them? Yeah, procedural seems better
Hey I'm trying to remake an old python game of mine, in it i had a window that was exactly 1366x768, the 'camera' was the entire screen
the unity orthographic camera doesn't seem to follow that exactly though, i can't make it fit a 1366x768 scaled up square sprite exactly
I can only get it to match the width or height, not both
not seeing the code question here..
if you want specific resolution try pixel perfect maybe ?
Hey, is there a way to have an variable of type enum? Like a variable that stores an enum type
Does that work đ¤
Enums are backed by a number of types, so just use that type, like int
Enum is a type and variable declaration is <type name> <name>
I think he doesnât mean store the âtypeâ of enum
I am unsure of the value of storing an enum in Enum (boxing, etc), but it does seem possible
i want to have an enum in inspector, which is dynamic and set via code
I would use int
how would I reach that goal with that?
or whatever the backing type is, and wrap it in a struct or something
enums are backed by an int by default, so just treat the int the same you would the enum
So, you mean a field that could be one of multiple Enum types? Or a specific enum and value would be set? It's not super clear
Flags
I don't think it's enum flags is it? Can you describe what the purpose is
Like layermask you can choose multiple value? If yes then flags
They didn't agree to multiple values, they agreed to multiple Enum types
They need to clarify what this is for
I think they mean like they have a couple enums, like
enum EnemyType {
Goblin,
Dragon
}
enum ArmorType {
Heavy,
Light
}
And have a field that could be either of those enums
My examples are obviously probably way off
exactly what im looking for. Im not even sure if thats what will reach my goal so I'll just explain my problem
That would certainly be best haha.
XY problem
Even if it is possible then how you can differentiate the value in your code, as vertx says they are int
Presumably they would need to declare another field next to the int that describes the type
okay its a little complicated and im tired so my head cant wrap around it.
I have a dialog class which stores a string and a List of Options.
Each option now has multiple Conditions. A condition references an SO, which stores just a value and checks it against another value of the same type with an operator chosen from an enum.
So i have a generic scriptable object with value of type T, and I'd like to have one generic condition class which can manage all the different operators that the types would use to compare to one another
what values are being compared here
ints, bools, classes, pretty much everything
I can think of some terrible ways to do it on the editor, but usually you need the known type so it can be serialized
I was trying to do some easily expandable way, but maybe its just no good to try
meaning that compare value field needs a specific type to probably show up in the editor
I can also just make 2 more scripts for each type i want to compare
So, I'd relate the field to the type of script like you have here. If we know it's containing an int to compare then you need to show a compare value field of int
thats the problem, I want to assign the SO (Value) first, then check its type and then choose the operator and compare value
so conditions or w/e this script you're using to display in the editor should contain all methods of comparison and change (what's displayed on the editor) depending on script type
which requires custom editor / showif hideif attributes
So I have one member for each operator enum i have?
Yeah, declare values but don't instantiate them if you're not using
or rather you have a value for each type that you want to compare
probably need to make different enum types depending if it's a bool or value type too
(or maybe a way to restrict what's displayed on the editor on the enums, but that sounds like more work)
Is it possible to open a mobile devices keyboard by tapping on an input field in a webgl build? I'm running 2022.3.
I think the keyboard does automatically open through active input fields
That's what I thought. But after publishing my build it didn't open on my phone or my wife's. Might be missing a setting or something.
there is methods to request the keyboard from the device, but I don't think I've used them
I usually prefer to develop an in-game keyboard anyway because some device keyboards are too large
If it was a larger project I would make my own. It's just a small project to keep me busy over winter break and mobile was an after thought tbh. If it's not going to be a quick thing I'm just going to cut it. Thank you for the help.
How do I reference a point relative to another object? Basically, "move object to 1 meter in front of this other object"
object's position + object's forward direction * units
you cant reference a "point" (value type) at least impossible in managed language
i meant a position
so calculate it immediately when you need it (then cache it if the value is immutable)
https://hastebin.com/share/qabuwucici.csharp
The weapon seems to be moving along absolute axes, and I don't understand why
could you clarify what you mean and what should it be doing
When I move right, the shotgun should move right. When I move forward, the shotgun should move forward etc. Currently, it does that just fine... until I rotate and everything messes up.
The weapon's movement relative to me changes depending on my player's rotation in worldspace, which I don't want.
is the gun a child of the player
An indirect one, yes
as in not child on the hierarchy?
It is on the hierarchy, just some layers down
so the player's rotation is affecting the children, yes
Correct
well, it does make sense to keep it a child
but if the local rotation values are messing up how you want it then make the gun a sibling to the player and just update the position directly through the script.
I would prefer not to do that... is it possible to fix the problem while keeping the gun a child of the player?
im not exactly sure of the precedence of setting the rotation with the local rotation also setting it, but you can try that, otherwise there's things like animation constraints which is some unity component
I'm not sure how that would help
All I want is for the weapon to move with the player's velocity
can't really make out what's wrong with the rotation on the weapon in the video and how rotating is affecting the gun, but if the gun is a child to the player it'll always move with the player, so perhaps some additional logic for how far the gun can extend from the camera depending on the velocity is my guess (via local coordinates)
Oh, I see what you're talking about now. It's a little subtle but I'm not sure why you've got rotation affecting it. It should just sway in the direction of the velocity, or direction the player is moving in.
Yes, thank you
well, velocity implies direction ;p
I mean, yeah it does... I'm not really seeing the problem with what I said? Sorry, I'm not as experienced with Unity & terminology so I'm not super good at describing problems yet
oh, I was agreeing with you. I was just stating that the direction of the player could just be represented as the velocity given to them.
Isn't that what I wrote in the code?
Oh, you may want to use lerp here, not slerp
slerp is spherical rotational interpolation
I actually didn't see your code there, my bad.
lerp looks wrong too btw
It really doesn't seem like that would be causing the issue, though
What should I use
I'm putting 0.001
swayspeed is 0.001?
not saying it was but still wrong
It's a direction issue, not a magnitude one'
Multiply by Time.DeltaTime?
not saying its prob ur issue but def something you should fix using lerp
https://unity.huh.how/programming/specifics/lerp/wrong-lerp
In a 3D project, is there any way to make vector arithmetic work with transform.position in 2D?
example Vector2 direction = vCenter + vAvoid - transform.position;
operator '-' is ambiguous on operands of type vector2 and vector3
or is my solution to break it up into x,y components each time
cast the vector3 to vector2
No if the z value will be discarded then dont waste time to compute it (if not involved in calculation)
yeah not worried about the Z in this case. Just trying not to rewrite a half dozen of vector operations as adding components
Ok, I'm using MoveTowards. How do I fix the rotation thing
There's a scene + assets in my project that's loaded with addressables. I am reading that I have to convert any prefab loads via resources to addressables in that scene? Is that right? Couldn't I just take those prefabs and put them in the scene itself to bypass having to do that?
hello im a bit confused about unity's matrix.
this gives me (0, 1, 0)
var mat = Matrix4x4.TRS(new(0,1,0), new(0.7071068f, 0,0, 0.7071068f), new (1,1,1));
print(mat.GetPosition());```
while the same code in System.Numerics gives me (0, 0, 1)
```csharp
var scaleMatrix = System.Numerics.Matrix4x4.CreateScale(new(1,1,1));
var rotationMatrix = System.Numerics.Matrix4x4.CreateFromQuaternion(new(0.7071068f, 0,0, 0.7071068f));
var translationMatrix = System.Numerics.Matrix4x4.CreateTranslation(new(0, 1, 0));
var mat = translationMatrix * rotationMatrix * scaleMatrix;
if (System.Numerics.Matrix4x4.Decompose(mat, out var scale, out var rotation, out var translation))
{
print(translation);
}```
why ? does unity matrices work different or what
I haven't looked into your numerics TRS logic, but it doesn't make sense that the position you get out of TRS would be anything other that what you put in
Your TRS logic is likely backwards
what does backwards mean
The multiplications are back to front
when apply transformation usually => p*s*r*t
so it should be s*r*t