#archived-code-general
1 messages · Page 295 of 1
not exactly, but you can definitely use this information especially to figure out where on the collider you should count as being
again: .Distance can tell you if mario should count as being on top of the goomba or at its side
so if you need to know if the monkey hand is supposed to be gripping a ledge, that is a good use case for calculating penetration
.Distance also gives you a unique point of the colliders along that line that would be in contact once displaced
i dont think you understood what im trying to do
isnt vector3.idtance just the distance between two points ?
i’m talking about Collider2D.Distance, which is equiv to Physics.ComputePenetration
Collider2D.Distance has absolutely nothing to do with Vector2.Distance and Vector3.Distance
Collider2D.Distance and Physics.ComputePenetration take in two colliders, and output the minimal translation vector to get them to be in contact exactly.
unlike contact points, these two methods (for 2D and 3D respectively) give a unique vector and point of contact to work with
you need to generate a unique result (ONE normal) to work with. And it needs to be an actual normal on the shape.
Hi, I have a project in Unity 2022.2.6f1 . I am trying to make a Roslyn DiagnosticAnalyzer work with additional .resx files. I was advised to provide those in our csc.rsp file since the project has multiple .csproj files, in the form of -additionalfile:"Assets/path/to/the/file.resx". However, if I do this, while there are no compile errors according to Unity and the analyzer does work on the codebase, somehow no scripts are attached to any prefabs or scenes anymore. Any advise? (not sure if this belongs here, or in #archived-code-advanced, or somewhere else
)
The worm wiggle
My magazine and gun both have rigidbodies on them and that is clearly causing problems
I was hoping making them kinematic would make them play nice but..
I don't want to use layers to fix it. How else?
are you mixing Rigidbody and non-Rigidbody movement?
maybe you should turn the "discrete" to "continous" collision detection..?
..yeah. The magazine is supposed to be adjusting itself to the magwell in Update() and onBeforeUpdate
Yet it stays in the same spot, strangely
I do the same thing for the gun onto the hand position, but clearly the rigidbodies here are messing it up
This is your problem
don't mix physics/non physics motion
When you put the mag in the gun, make the rigidbody kinematic
It is.
That's why it doesn't fall
if I make it physical, both objects do the worm wiggle
hello. how get how many pixel is visible in sprite? im using masks and need the visible pixels percentage
int totalPixels = image.GetComponent<SpriteRenderer>().sprite.texture.width * image.GetComponent<SpriteRenderer>().sprite.texture.height;
Texture2D maskTexture = image.GetComponent<SpriteRenderer>().sprite.texture;
Color[] maskPixels = maskTexture.GetPixels();
for (int i = 0; i < totalPixels; i++)
{
if (maskPixels[i].a > 0)
maskedPixels += 1;
}
print((float)maskedPixels / (float)totalPixels * 100f);
im using this now but not work
!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.
it would be kinda complex. You'd have to find the areas of the screen in which they overlap and then check the mask alpha (against mask threshold) at each pixel only in the overlapping area
also pixels in the sprites don't correspond to pixels on screen
It would be better probably to do this with a shader
output a texture and count the white pixels for example
hey guys?
my PlayerStats and Experience is finish now...
but now iam tested it inGame...it works fine, but have a little issue:
if there added in short time XP...then the calculator dont work correctly...
he use then the current value from this add, not the target value from last add...
(if i wait to finish the last add, then it works fine)
Hi. I want to make a card game. The properties of each card is stored in a scriptable object. I want to attach the abilities there as well but I can't attach scripts. Is there a workaround for this?
The Scriptable Object:
using System;
using Unity.Netcode;
using UnityEditor;
using UnityEngine;
public class ScriptableObjectIdAttribute : PropertyAttribute { }
[CreateAssetMenu(fileName = "New card", menuName ="Card")]
public class Card : ScriptableObject
{
public string cardName;
public string ability;
public Sprite art;
public int cost;
public int power;
}
well, maybe i should say that i add the XP as float time
so you want to attach the scripts to the cards in inspector?
yes
whait a second, i haved this problem in past too, i look how i have solve it
wdym by "attach scripts"?
You mean MonoBehaviours?
Those can only be attached to GameObjects
public List<string> additionalScriptNames; // Liste der Namen der zusätzlichen Skripte
// Zusätzliche Skripte hinzufügen
foreach (string scriptName in additionalScriptNames)
{
Type scriptType = Type.GetType(scriptName);
if (scriptType != null && typeof(MonoBehaviour).IsAssignableFrom(scriptType))
{
enemy.AddComponent(scriptType);
}
else
{
Debug.LogWarning("Skript \"" + scriptName + "\" wurde nicht gefunden oder ist keine MonoBehaviour-Klasse.");
}
}
Backticks, not apostrophes
```
I want to be able to drag a script there like I can with the sprite and make a function that adds that script to the gameobject when it is spawned
with that you have in inspector a string list, there you can write the name of your script what need attached...
(just the name, not .cs)
Not really possible. You could make a prefab and reference the prefab here
then instantiate the prefab as a child
thats true
I will try this. Thank you.
well then use my code, i use it to attach scripts to spawned enemys
Was able to get my single sound effect randomizer working that changed the pitch/volume of the sound effect to make it seem like there were more than just 1 sfx. It created a new AudioSource for each sfx playing--which created a lot of garbage, so I implemented object pooling for it and now it seems to work well
anyone have idea for that?
What depenceny injection packages/libraries are recommended nowadays? Most solutions I found were not updated for years
Extenject and Zenject are the two most common I see.
Mostly people just roll their own though afaik
The speed at which you add experience should not affect the calculation . . .
I am trying to create a save and load of the PlayerData but I am experiencing difficulties can anyone guide me ?
!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.
!bug
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
!logs
why are you spamming commands dawg
if i have a game object name of a game object i have to destroy. How do i find that game object in the list by its name.
GameObject.Find
totally not recommended doing this
^he does not recommend it because it is generally considered best practice to keep REFERENCES to objects, rather than finding them by name, for performance reasons.
not only perfomance but its also very very brittle
I know that gamobj.find is slow but why? Is it really that expensive to go down the list of objs in the hierarchy until it finds the right one?
strings , reflection, scanning all objects. All mix for a bad time 😉
but what if one frame loses a reference to my variable! It's sooo much better to run GameObject.Find("MyObject") in the Update() loop so that it will never lose the reference 😄
the same reason you should never have tangled headphones
what if the sound gets lost along the way?
exactly, and since my pocket tangles my headphones anyways, I pre-tangle them before putting them in my pocket
https://hastebin.com/share/ziwaberidu.csharp
Even if the player is on top, he doesn't take it with him
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
are you colliders set to is trigger?
platform have 2d box collider is on Trigger
how do you have it setup in your scene? is the player on the elevator instantly after play?
wait
so the problem is that the elevator isnt going up or the player isnt being parented?
? i don't have error in the logs
doesn't write either
then its a collider detection issue
I have a collider box in trigger another one without trigger and a rigid body in kinematic are all 2d
either your player doesnt have the player tag or you colliders are setup wrong
those are the only options
player have tag Player for colliders i don't know
How would you generate a random int that is max inclusive without adding +1 to the max?
Say, I want random between 1 and 1 or random between 1 and 3.
First should return 1, second 1, 2 or 3.
Random Range is max exclusive for ints
between 1 and 1
this case already exists, random.Next(1,1) will give you 1. But yea just add 1
I knew this had to be simple since google had nothing for inclusive int,int random lol
Following a tutorial on inventories, but I can't figure out how to make this accept the eventData from the OnDrag event using the new input system. Can anyone help with this?
I'm struggling to figure out what exact syntax it's wanting, for me to add the pointer info that it needs to function.
public void OnDrag(GameObject obj, PointerEventData eventData)
{
if (mouseItem.obj != null)
{
mouseItem.obj.GetComponent<RectTransform>().position = eventData.position;
}
}
And here's the function that that line is associated with
https://www.youtube.com/watch?v=ZSdzzNiDvZk&list=PLJWSdH2kAe_Ij7d7ZFR2NIW8QCJE74CyT&index=5
Also, if it matters, here is the tutorial I am trying to follow to create my inventory system (though I'm using a list of structs instead of a dictionary, due to some behavior I didn't want)
Item swapping with #unity3D is the 5th part of my Inventory System playlist using Scriptable Objects!
Source Code: https://github.com/sniffle6/Scriptable-Object-Inventory
If you like this channel, or just Unity in general, consider joining my Discord at: https://discord.gg/5yj4Ecp
*************************************************************...
Any help with this would be deeply, truly appriciated.
but it do
Here's a pastebin of my script, and the issues start at line 246. I basically want these events to read pointer data for the mouse's position, but I'm not able to figure out exactly how to set this up.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
and i cant to share my code here, bcs i dont have nitro...
nitro has nothing to do with sharing !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.
Hey is there any reason why it cannot find the folder in my Desktop? Is there some sort of access rights?
use a third-party code pasting solution
ye if i make cs
then discord say me its to large
because you're supposed to use paste or bin sites to post/send large code blocks. trying to paste the entire code in the channel will take up too much space . . .
I would use Application.persistentDataPath instead
check the links from the bot i posted above . . .
#archived-code-general message
I tried that but same thing
if i add 1time XP and wait for the end of the slider value calculate, then it works fine...
but if i add in short time more then 1time XP then it dont works fine...
its up to you, but you could use a library like LeanTween for the level up animation...
the lvl up and normal animation is same, the only different is the amount...
and the animation isnt the problem...
just the calculate if i add in short time few times of XP
My script Kia is this: https://paste.ofcode.org/vw6qe5U2XcgTuvaQG7wzmx
and it is iterating through sprites kia (not kia1)
However, it only changes to sprite #2, and does not change back to #1
Can someone help?
So my gun has a bunch of colliders, and my magazine has a bunch too. When I insert, it makes the whole thing freak out cause 2 rigidbodies are in eachother. How fix?
I don't want to use layers
There are many colliders and I cant do physics.ignorecollisions on all of them
I just want to make 2 rigidbodies have all of their colliders ignore eachother for some time
why do you have rigidbodies on each section? colliders should be enough
The magazine and gun are two separate objects.
They are independent of eachother.
VR btw
oh then your question would be better in #🥽┃virtual-reality
I have never gotten an answer from there.
This isn't exclusive to VR so I think it's okay here
Why cant you do IgnoreCollisions on them..? That would do exactly what you want
And why would a magazine have many many colliders
Doing that method for every combination of colliders on each object? There's 3 on the mag and 12 on the gun
Sure, or just the comliders that can overlap
Or just remove the magazine's rigidbody when you insert it
The colliders would still mess with the gun, I think
If you make it a child of the gun then it will be part of the gun's rigidbody
Multiplayer game, can't use parenting
Well, if there's no other way, then I'll do the combination thing
they just do it using physics
Wait why can’t you use parenting in multiplayer
Seems like an important part of hierarchy to not have access too
Hi people 👋 is anyone experienced with unity version control. I’ve set up a project with my collaborator but whenever he downloads the project on his end the folder is empty,
could I have missed a step? Please advice if you know. Thanks
I use git, but it is similar. Have you commited your changes and pushed them to the cloud?
so i'm making an ability system similar to GAS in unreal and am having issues coming up with a way to deal with "reverting effects." So like a temporary slow, or something like that. Any suggestions?
in unreal
I clicked on Check in changes. I assume this pushed it to the cloud. Is there another option ?
... making it in unity, similar to GAS in unreal
With a networking library that does rollback (going back in time to correct mistakes if the client disagrees with the server) like Fusion, doing parenting is very hard to manage with that.
Whereas with regular values like floats and vector3s, they can be simply saved and stored in a previous state
Not so much with one way actions like parenting
Suddenly multiplayer sounds much more daunting to set up
how do you handle simple things that normally use parenting such as moving platforms though
Dude, it sucks. Multiplayer is the hardest thing you can do in game development.
But it's all worth it, nothing beats playing a game with your own players
The first game I’m trying to make is meant to be a multiplayer game so I’ve been trying to future proof all my code for when I implement it
Stuff like moving platforms is handled manually, but in the case of Fusion they provide a very comprehensive (and surprisingly easy!) kinematic character controller all made to work with multiplayer and moving platforms.
I tried the same thing with my first ever project, the first task was to learn Unity, and then convert it over to multiplayer.
Not gonna happen, lol. There are so many structural differences that in the end it's just easier to start over, bringing over only your assets and 25% of the code that could still be used in multiplayer.
So I would suggest dedicating this to learn as much as you can about Unity and C#, then starting fresh with some multiplayer samples to learn networking.
Luckily in my case I haven’t gone too deep yet so I only have a dungeon generator and a player controller that I was planning to change anyways
To be clear, you can use parenting in multiplayer, but most modern networking libraries do this thing called prediction, you can see it in action in multiplayer cause your character moves before getting a ping back from the server. Your client is predicting that it can do this, so it does it locally first to give the user a very sharp response.
Make it so the change isn't destructive. Then you don't have to revert the effect, just remove it. As in, the effect is "applied" by evaluating each effect that is currently active at any given time.
If for some reason, you actually couldn't move in that moment (like if you were already dead on the server) but you did anyway on your client, it will do a rollback. This means rubber banding you back to your old position.
What happens with parenting, is you need to specifically tell Fusion that if something goes wrong, you need to unparent it to roll back
I just found moving objects regularly to be less of a headache
So parenting is only an issue with things that are changing basically, but if it’s something like the generated dungeon with one time changes it wouldn’t matter?
Oh well yeah, cause there's no case where that could go wrong. Everyone needs to generate that dungeon on their client.
It's only a problem if there's a chance that the situation is different on the server than on your client, so your client does something impossible and then needs to cancel it (rollback)
i just took a look. elapsedTime is used incorrectly for the lerp, and it seems your coroutines are overlapping each other, which is probably causing the experience issue . . .
Glad to know I don’t need to convert that in some way, it’s complicated enough already lmao
i'm not sure exactly what you mean, do you mind taking a look at my code? https://gdl.space/ibiwexerek.cs
i have it somewhat working, but it feels hacky
What I mean is that you don't save any "current" modified value. If you want to know the current modified value, you take the base value and apply all the current modifiers on it. Then if you want to remove a modifier, you just remove it from the list. The next time you calculate the modified value, that modifier won't affect it.
What does that mean?
the friction from the physics system makes the wheels rotate by themselves
Yes but it won’t make the chassis rotate
Therefore I don’t know where the rear wheels go.
uhhh, can you explain a bit more?
When your car steers what happens
You turn left sure if ur steering left
oh i see
But your front tires move in the direction of the steering direction
But your chassis rotates
But in real life it does
And I need to simulate it
ok,in that case you should just rotate the forward vector
Wdym
The car doesn’t rotate to the direction of the wheels
essentially this
an object rotating is basically this
two vectors
Yes
your forward vector
This is the car rotating around the ackermann point
and you add a sideways force to that forward vector
yup
But how would that actually make the car rotate
you are moving sideways as well as moving forward, thus causing the rotation
Ye but I can’t rotate the car just by adding force
or maybe you could just cheat your way out and rotate the car itself a small amount, causing the car to steer like it should
Then it’s not realistic
can you add angular foce?
When a force is applied at different direction on 2 different points of an object(presumably on different ends from center of mass), it would rotate.
yes
Think of a needle of a compas.
That’s a thing?
yes
But how would I do that to a gameobject
think of it as when you rotate a valve
You can apply force to an rb at a certain position
Oh fr. Holy shit I saw a YouTube video abt steering and that’s prolly how he did it
Then I won’t need to calculate rear position because it’s a child
🙏 PEAISE RHE FODS
Sometimes good to check the API docs to see what methods and properties are available.
i see
https://gdl.space/reqarehoxa.cs
For some reason whenever this code is run it crashes at a certain point that seems to be different every time. Im not sure why. A very similar but slightly diferent verison of the script worked just fine, and ive made sure it isnt any of the scripts that this references, so im not sure what the error could be
Is it an actual crash or a freeze?
This is probably a freeze.
That while loop in Spawn has a lot of potential for being an infinite loop.
i thought that too but i cant see a reasaon for it to be if it is
Since you're asking in code general channel, you should know how to use a debugger, so use it when the freeze occurs, to see what the code is doing.
i would add a max iteration counter to that while loop and attach the debugger with a breakpoint. if the if statement in that while loop is never true then tempVal never changes
I have found a C# course that is working for me. Perhaps it will help others too. I have to play at min 1.5 speed though
https://www.youtube.com/watch?v=DSbgl48VFLg&list=PLJitdQVsSaf7nHcznVnW7ALB2K514QKk_
If this course helped you, please click the THANKS button and help support our channel! It took many many weeks to create and edit!
Your THANKS comment will be highlighted so that everybody can see how awesome you are!
Thank you! :)
Hello! Welcome to C# Programming for Absolute Beginners!
Here you can learn C# from absolute basics...
what you mean with "i use elapsedTime incorrectly"?
and why should the coroutines overlapping each other? the first coroutine will stopped if not lvl up, and start the second if lvl up...
they never can overlap each other...(assuming I only start 1 process to add XP)...if i start a second then sure, but thats the question, that is what i ask here...
so now i need ask a second question...
thanks that you want to help me...but how you help me if you explain (just with other words) the problem what i explained before?
So I'll explain it again so that the last person understands what I'm explaining instead of trying to explain it again without helping me😪
If I only do 1 process to add XP then it works fine! without problems!
But if I start several processes to add to XP in a short time, and then
e.g. from process1 the XP should go from 30 to 50...
and at 40 another process is started, then not the 50 + new process, but 40 + new process is calculated... so always the value at which the currentValue is currently in the change process, instead of the value where the currentValue should go...
Use the proper method to paste !code plz.. mobile guys see this
📃 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.
alr it is kinda goofy seeing that
Ya. We have to download the file and go find it to open it..
heres a simple script that will help https://paste.ofcode.org/32AQpZAH8dxzcw29YKDRcHg
bet if change the object to a list with a wheel class it would do better
Ya looks decent. Covers the basics.. A list or array would def clean it up a bit.. I use two arrays 1 for the rear wheels bc sometimes I like them to do something different
Oh have u made a car before
I’m not using wheelcolliders btw
I made mine with a big sphere collider.. like a hamster ball
well if your looking for it to be realistic like you said its better to uses them
It defeats the purpose of the project a bit tho
Also there is no steering in that script
What is the purpose of the project then? And yes there is steering
private void HandleSteering() {
currentSteerAngle = maxSteerAngle * horizontalInput;
frontLeftWheelCollider.steerAngle = currentSteerAngle;
frontRightWheelCollider.steerAngle = currentSteerAngle;
}```
Oh sorry I couldn’t see it from my phone
Lol phone slow
I appreciate the help but unfortunately it won’t help with the project
You still haven't said what the purpose is, or why it wouldn't help
I’m doing it from the ground up
Hmmm... so you don't have any rigidbodies or use physx? You're just doing math and setting the transform with manual spatial queries?
Tough. But kudos
Realism is wheel colliders or a form of them.. Arcade kinda just translates and the wheels are more just graphics
Wheels should be child of car anyway and should roll with the chassis
That’s the plan. Though I think maybe it’s a bit too extreme for a first attempt at cars though I won’t use wheel colliders.
I think I’ll use a rigidbody in the chassis
And apply forces at specific parts of the car causing rotation
Yes
And I’ll code the wheels myself
Including slip and stiff
And also calculating steering angle
Cause ima do ackermann steering and I will need to code differentials
have looked a unity's source code
bouncy
just axle points and math
No, why?
never got it to drive good tho
too slippery w/o wheel colliders.. and i never wrote any friction forces
That’s no wheel colliders?
ya, its just applying upwards forces at each sphere u see
Oh u used unitys fric to on
Friction
I just used circumference of wheel to tackle distance
And will eventually apply slip
ya this is the only part i skipped
if i go back and add some slip / grip to the points where the raycasts hit the ground (but apply it to the car) it'd feel alot better
Rn I’m doing this in unity and Roblox studio. Roblox to make money and unity to make something quality
Roblox makes it too easy dawg
good luck on the car..
Wheels work on the ground too easily
lol
car controller and character controllers always eat up so much time trying to get them to feel good
Appreciate it. If h wanna join on the project feel free to lmk
I agree.
it is absolutely worth it tho
a player may just quit playing just because controlling something just feels weird
have your tried a physics mat
not yet.. since the car floats there really wasnt a need yet
i just apply forces and torque to the floating collider
What’s that
physics material
absolutely, and not to mention the re-useability.. if u nail down a good controller u can package it up and re-use it as a base for every other project
yessss
That’s the problem with Roblox. Every Roblox car handles like shit
been perfecting mine since 2020 ;D
What do you guys think is better for shooting projectile bullets:
_rigidbody.velocity = transform.forward * speed;
_rigidbody.MovePosition(transform.position + Vector3.forward * (_projectileSpeed.Value * Time.fixedDeltaTime));
i use the first one.. can't say which ones better
Why is ur rigidbody hidden 💀
grabs it in Awake() i imagine
yep
first method looks alot easier too..
I was getting alot of of shooting in one position rather than using velocity
he uses getcomponet
GetComponent<Rigidbody>().AddForce(transform.forward * force,ForceMode.Impulse);
I was told Addforce might be a bad idea doing a top down shooter
maybe
Depends on the person and how they code their movement . . .
your right
I just looked it up Velocity moves the object at a constant rate vs Addforce only pushes it which has a way of stopping at some point
if u dont use gravity i wouldnt see where addforce would be a problem
even on a top down shooter
U made that?
ya
Beautiful ash
Sounds like a fair compromise. Cool project. You'll definitely learn a lot
ty
I see so using gravity would be better to use addforce to simulate gravity within bullets
I think so too. It’s just frustrating because you want to make it realistic but you want to make it possible
What about moveposition
ive only ever used moveposition on a character type rigidbody
never on a bullet.. so idk
Yeah I used it for moving too but it also ended up jittering
crank up thta interpolation 😅
working on a checkpoint system
MovePosition on a bullet would require you doing all the physics yourself. It is meant mostly for kinematic rigidbodies
addforce with no drag/gravity, or velocity = i think are u two best bets
Appreciate you so if I wanted to make more dynamic bullets down the line Im guessing Addforce is the best one
Yeah, just one call with ForceMode.Impulse is super easy
do yall this is a great implication
is that
?
Just so I make sure.
Velocity - for constant movement
Addforce - for more realistic bullet movement
MovePosition - For more character based movement
Namespaces r used a lot? I didn’t think so
AddForce has different ForceModes. so its a variety of things it can be
I mean, no.
MovePosition is for kinematic bodies.
AddForce is for the physics engine to handle velocity and reactive forces for yoy
Velocity is to give you more control
i used Impulse in my example.. so its all the Force at once
The last two are for dynamic bodies only, meaning you HAVE to do MovePosition or rb.position = for kinematic
Ur username just rung something in my head
namespace is mainly for the assemblys
Like a year or two ago you just started out
ya, its going on 3 years or so now
Lmao that’s funny
still hanging in there 😄
I’ve been running year-long breaks
as long as u dont forget too much between, lol
Appreciate it guys
So like utils?
Forgot it all
it make sure i don't compile unnecessary things after changing something in the code
namespaces are like collections/groupings of code that are related
helps speed up compile times
Ah ok
Utils is a decent example
Smells like a library
namespaces and assemblies are unrelated
ya, my ide doesnt even sort with namespaces (i havent figured out how to yet)
Namespaces are just handy organisational groups that make it clear how things are differentiated
assembs, yea
Assemblies are functionally separated groups of code that can compile differently for different platforms and define relationships with other assemblies
no they are
namespace is the grouping
Nope. What you're seeing are assemblies.
Namespaces are like last names, if you have two dudes named Tom then you can tell them apart by their last name.
Assemblies are like families, you can have hierarchical relationships between different families, but it has no real bearing on somebody's name, and the only connection between that and namespaces is that it's convention for people in the same family to have related last names.
it feels like i am a kid learning again
does unity have any built-in timers? or do i have to just substract delta time over a float?
don't mind if i save this
Mainly I use namespace so fleet is happy
There are coroutines
And async
how much control do i have over those?
like, for example
Well... complete control of course
It kinda is, but it's got more of a focus on cloud integration. Sadly when I tried it about it year ago it was really bad, but it's probably improved since then
Part of why I like Rider is that it just works, and it works well—which Fleet absolutely did not
if i wanted to add time stop, would i be able to completely pause the coroutine?
You would have to cache values, and stop the coroutine afaik
You would then restart ut where it was
Or you could possibly have a bool to prevent it from "running" while it loops doing nothing
Like an early return, but just yielding
funny little promotion image.. could u imagine? "hey bro get off my line!"
i was looking at implementing IDisposable on my Items (poco), so they can destroy an instantiated SO when needed. This SO is instantiated in the ctor, initially I destroyed in the dtor but apparently the dtor isn't always called.
From what i see online, it looks like im required to call Dispose myself. Is there some way to have it automatically called when its not referenced by anything? Right now im concerened about in the future, if one class ends up doing
public void MemoryLeakSimulator()
{
new Item();
}
Ill have an instantiated SO just sitting around with no way to destroy it myself
I was planning on using a poco instead of the SO, but im still curious if such thing above is possible to solve.
Is there some way to have it automatically called when its not referenced by anything?
No. Only the dtor, which you generally shouldn't use
I guess my solution is either guarantee i dispose everywhere, or not use SO here still then. Thanks
if it was just a plain c# (non-unityobject) we can do this GC.Collect() and then check WeakReference.IsAlive then again who's in their correct minds would do that 😂
this stuff is a bit above me, so just asking even though i likely wont use it. Would this even be possible to enforce with the case above of some class just calling new Item() only? my Item class is a poco, but it holds an instantied SO
I'm not sure the side effects are due to you have a reference to unityobjects in there
also it's not worth tho, gc.collect is slow af
Sadly you should just call Dispose, that's how it's intended to work
Just as you should call Destroy on any UnityEngine.Object types you allocate (even those allocated by material calls)
yeah, even if it's just a plain c# class, weakreffing has a limitation once it's successfully being weakrefd, you can't keep it for a long period of times due to it might be promoted to gen2.. also not sure if gen2 stuff exists in il2cpp
Yea ill just rework this so i dont instantiate an SO. Then Item gets destroyed, and the poco inside will also be destroyed i believe.
I've never really looked too deep into gc or memory stuff works so this has been pretty eye opening
No managed memory is released until all references are null
and UnityEngine.Objects aren't released unless Destroy is called, or a complete scene reload occurs, or Resources.UnloadUnusedAssets (which is very expensive)
to be clear, UnityEngine.Objects have native and managed parts, and so Destroy doesn't release the managed part
For example, with a reference to an SO that has a reference to a managed object, calling Destroy releases the native memory and the SO will evaluate to null, but the managed SO and its references are still in memory until you also set the reference to the SO to null
how do i change a single color from a color block?
do i need to make a new color block and the nreplace the original one?
ye
What is a color block? Haven't heard that term
this thing
has to do with buttons
selectables seem to have it according to unity docs
you replace whole thing iirc
Gotcha gotcha. Thanks
yup, did that and it worked correctly
i think i understand, thanks for the explanation
Any linux devs here?
You're probably better off just asking your question https://dontasktoask.com/
This is the code related general channel.
not impressed
Literally the very first one on linux
Which makes reverse engineering (and cheating) on linux games substantially easier
what you're flexin about, me don't understand
literally not related to unity
Linux anticheat is ass, which is usually balanced out by linux game-reversing tooling also being ass
I just made the tooling way better
Your engine uses pointers bozo
all games made with Unity are easy to reverse enginered already
😅 I don't understand this
Congratulations here's your duck 🦆
Ty hehe
I'm not finding much on dependency injection and it's practical use cases in Unity, is it just not used very much?
Trying to sort out how it fits in with delegates/scriptableobjects/monobehaviors
I once used ghidra so technically im pretty much hackerman too
You should put your game in DNSpy
Was really funny seeing the gamedev course guys at my uni do this to their unity games
aight, now it's time to learn c#, here https://learn.microsoft.com/en-us/dotnet/api/system.type?view=net-8.0
you can brag about it once you're done
Ew microsoft
I'll be honest you guys are safe because I don't want to touch c# with a 10 foot pole
Stack machines can btfo
aight you're just trolling in here
ya, it seems There's very few options for using Dependency Injection in Unity. just reading thru the forums.. quite a few posts discussing it..
C# being a stack machine us a legitimate complaikt
Complaint
The writings of Ashley Davis on coding, data, visualization, microservices, game dev or whatever is exciting at the moment
Dependency Injection though is pretty much the concept of object pooling
And I don't mean that it uses stacks for control flow, I mean that the c# virtual machine literally doesn't have more than like 3 general purpose registers
Which is aids
wait, what does object pooling have to do with dependency injection?
heres what that article covers.. its the most decent one ive seen so far
altho i dont know nothing about it tbh, just searching for ya
@hidden compass Yeah that might have some of the information I'm looking for, I wasn't having the best luck on youtube.
found it in a reddit post (screenshot from part2) of that article
Say you want to spawn an enemy with gun and bullets:
step 1: Dequeue EnemyMono
step 2: Dequeue GunMono
step 3: Dequeue BulletMono
attach em together, and bam dependency injection
technically all monos could be considered dependent on injection cause you don't have access to a normal constructor
Yeah that was one of the things I was trying to figure out, since they seem to overlap a bit.
Do you guys ever use non-OOP programming paradigms or is it infeasible for gamedev?
what like functional programming?
oop is pretty bad alone
Yeah
you need ECS or compositional approach to really have a manageable workflow
I mean you could, but from what I understand is that disregarding OOP for 100% functional programming seems like a bad idea.
Ngl, the fact that you guys have to consider design patterns this seriously is really cool
Access experiments at CodeAesthetic.io
Discord, deleted scenes, song names and more at patreon.com/CodeAesthetic
How is this different from OOP?
much
Of course?
ECS is over my head
OOP you can dig a hole pretty easily if derive your behaviours too deep, or spread too thin
Functional is a delusion anyway, its always imperative when serious work has to get done
ECS is black magic I don't have the inclination to understand
It's hard enough I keep replacing everything I'm doing over an dover.
I got halfway through converting to use a service locator, now I'm on to DI
Entities are an id
Components hold data
Systems iterate archetypes
Archetypes are entities with specific components, which exist in the same contiguous chunk of memory
Data Locality means an huge boost to performance when done right
I mean functional does not glue at all with the model of computation all machines are based on. Functional requires an imperative abstraction layer
With OOP you can fall into problems such that you have like an enemy
Orc -> RangeOrc
-> MeleeOrc
-> MagicOrc
But now the question is what if you want your orc to melee and be range? Do you make a MeleeMagicOrc? And this is the problem with OOP alone.
@spring creek Conceptually I kind of get it, and I've looked at some demo's of how it's setup, but writing something around it is a whole other pickle
I found it rather pleasant. I moved to Bevy almost entirely to chase a more ECS focused engine
Just takes a different way of considering it
i just re-iterate and try to plan out my projects so i dont have to worry about that Orc issue
Multiple inheritance?
Right, c# you have interfaces instead of that, but even then you can run into the diamond problem of multiple inheritance
It's too different than what I'm used to, Unity is hard enough when coming from something like a simple backend service.
Gamedev is hard.
if Unity's editor wasn't what it was I wouldn't have learned to code
Actually is
Guys that make game engines are just as insane if not more insane than OS devs
Is FishNet the general consensus for setting up multiplayer?
No
FishNet?
FishNet? is that new?
ive heard about that here recently.. didnt know what it was
Where did you learn stuff like this
There is no general consensus. Use whatever fits your project
Doing a little research right now and seems like Mirror was the previous one typically used
Is it the 'correct way' to use c#?
seems like FishNet is new
Mirror is easy to set up.. Lobby's Connections and stuff
Trial and error of making a lot of bad hierarchies and rebuilding them
Why did you stick with unity?
because Unreal forces blueprints and that's a job of its own
unity is a prototyping beast
Unrelated to the thing I replied to but still hoho ^-^
If I were to be more specific, I want to make something with small lobbies (2-4, maybe up to 8) hosted by one of the players. Not sure which would work best though since I’ve never set up multiplayer before
Must be insane to work at both such high and low abstraction
Research all the available frameworks and their features.
But generally, they all do the same thing under the hood, so it's a lot about personal preference.
I had to use java for the first time in yearssss recently and it kind of hit me how namespaces are just a default that you don't question
Or these fancy ass build systems
all of those mentioned that ive seen use their own servers to host games.. not sure about having one of hte players be host..
not sure what solution fits there
so you are looking for something that supports peer 2 peer?
Fishnet is aight, but their documentation is a little arse. I do think Unity's networking library is probably one of their best modules and a great starting point despite behind on some features.
Fellow 3:44AM-er
Do you guys write your own protocols for online play
All of the mentioned support p2p. In fact that's probably the most common use case.
Or use libraries that come with a framework that you just fill out
oh.. i didn't know that.. i thought they all used their own servers so they could cap player count.. and provide subscription services
They might be using lobby servers for establishing the p2p connection though
ahh perhaps..
That's what the lobby servers are about.
https://docs-multiplayer.unity3d.com/netcode/current/about/
Worth starting with since a lot of these libraries following similar concepts, and it's also 'free'
Overview of Unity's Netcode for GameObjects for your multiplayer networking needs.
TIL
Because it's generally impossible to host a server normally via home internet.
router will kill all incoming conn requests
Wouldn't be using P2P only be difficult due to network shenanigans like NATs, or is that not really an issue to think about?
You need servers to listen for connections, a typical home router doesn't let any connection request into a home network
I see
It is the issue. But the only way to solve it is to have a publicly available server that can connect the 2 clients. It's only needed initially to establish the connection between the two.
Though, I guess that depends on the framework
With photon I think all the traffic goes through such a server
wow, theres alot of documentation now for Netcode for GO
best documentation unity has put out
because there's actual tech docs that explain to you the process of it all
i might give this a try.. just to add a MP prototype to my list.. its been a while.. since I made a photon lobby / MP walking sim
Tricks and patterns to hide latency, what's acceptable to manage client side with client authority before sending it to the server, prediction, server rewind, action anticipation, etc.
so much effort placed into this it's unreal (I made pun teehee)
lol.. 😄
ya, all their docs need to look like this
pinned on Github now i just need a mp game idea 😅
speaking of docs, i want to know how everyone documents their code for their games? what tool is best to use? a wiki?
documents their code?
yes, like if i work on another project i want to come back and still remember how thing work
write readable code, or if that fails, write comments
yes, but maybe show screenshots of gameplay and what objects in screen is associate with code.. i cant embed screenshots in code, can i? unless i can embed links in c# or if i hover over a certain code a screenshot appear
That is a bit far
thank for input though
Generally if you take the time you name your variables/classes/methods ect in a way that will make sense to future you
are you working with a team? in small teams (or especially alone) i wouldnt waste time on this
and you don't make a bunch of monolithic hunks of code, it should be readable.
For some projects, if there is an API, I'll use doxygen and uml. But that's pretty rare.
I usually have a Readme in the project for the team, so when they grab a template from our repo, there is help getting going.
For bigger projects we do use an internal wiki. But I've been pushing the team to keep it to the readmes so they are versioned.
no, i work by myself for now. if i do open source project then that could be different case. which i want to in future. Otherwise contributor might scratch head what i trying to do
In my case, I have some very thorough all in one templates (especially in VR). So having a gentle reminder of how to setup something is always a plus.
thank, that soudn good
It's also helpful to document how to deal with odd VR frameworks that need special toggles and such. But wiki & readmes.
At the top of your code it's helpful to use /// three slashes for proper documentation. Then if you do need to, you can use doxygen later to generate code docs. And keeping it in its own namespace is always a good idea too.
it a game engine so maybe i also need to understand myself the configuration, for example game objects, references, ui layout etc., which i may need more than what comment provide
sound good
I find establishing some architecture in your code can help with readability later, since if you understand how a certain pattern works, and your code more-or-less follows that pattern, it should be easy enough to follow along your logic later, if you plan on templating your code or turning it into a framework or something open source, then adding summary comments can help for public functions and properties, the downside with comments or wikis, is that they also need to be maintained when code changes or gets refactored, or if you make certain functions, events, etc obsolete, and while working on a project, code changes often from my experience so it can kind of be an additional thing to manage imo alongside source control
You'd probably want to minimize where the problem is and if it's more network related, take it over to #archived-networking or the photon server
you really wont get better multiplayer help here. a lot of people here dont even touch multiplayer and wouldnt be able to help you with photon specific stuff
I use http://www.notion.io it's easy to post screenshots/video clips and codeblocks.. I also have a index of systems and todo lists
Github is another good place to document ur code.. if you learn markdown you can make some good Readme files with images and all that
I've been using it for school notes and it's been really nice. Being able to do inline LaTeX is super helpful.
Can get really complex with it if you want
I've only barely scratched the surface
Oh abs.. I had to put it aside. I was starting to color code everything.. had an index list of emoji as symbols n all
how do I conditionally show fields in the inspector, for example only reveal certain ones if a certain enum is set to something
I figure its possible with an editor script
yes, write a custom inspector or use something like Odin Inspector
So I've this dilemma on when to remove an object that's contained and managed by another class. When I access this object, should I allow to return the reference and keep the reference contained in the manager? Or should I always remove the reference from the container when it is to be accessed?
For example, should I have a method of:
public bool TryGetAndRemoveObjectAtIndex(int index, out Object obj)```
Otherwise, who should be in charge of removing these references from the container if the object is consumed?
Pretty much dependent on your usage pattern.
And I mean, you can always have both, like Queue<T> has both Peek and Dequeue.
For instance, an inventory with a health potion. You can access the inventory and grab the reference and drink it -> the object is consumed and destroyed.
Two ways I can see handling this, one being to just remove the health potion as I access it and let the health potion destroy itself, or reinsert it later if it's not to be consumed (and only modified)
The other way is the health potion needs to do a callback to the inventory and tell it that it's to be destroyed and remove that reference.
Or maybe even let the handler manage the usage of the potion instead?
I think the biggest issue is keeping track of references that would be modified, but still be active in the inventory.
Perhaps the modification consumes it in the proccess, now I would need to remove it from the inventory x_x
Maybe the idea is to just keep all behaviors on the items themselves private and bound by a delegate and let the manager call the Use() methods and such
thanks works amazing
how do you manage comments on both interfaces and implementations when you just want them to sync?! 
Usually if you stick a comment above methods you do get some of that information when you hover over the methods elsewhere, but im not too sure if that works with interfaces
It's not just a comment above a method which will give you info.. it's a particular type of comment. Do three /'s above it and it'll give you the summary comment, which allows you to add the params/ etc
Do you have to create all scripts in Unity or only monobehaviors?
So Unity creates meta files
Which afaik are needed for things like showing script in the inspector
The meta file has nothing to do with where you create the script, they automatically get created for everything that gets put into the project.
Don't even need to make a monobehaviour in Unity.
They are not created when I make a c# file in VS, someone told me before to always make them through Unity
We had this issue before
Is that not the case?
I've never not created them in unity, because.. why wouldn't you 😄
But I don't see why it would make a difference.. Unity auto creates a meta file for everything in the assets folder
Just tested it, created a new class in VS.. saved as into my Unity projects scrips folder.. meta file is created, as expected.
Me every time I add a feature in my game: "whew, got it working, let's go on to the next thing." Me when I need to change that feature: "wtf was I doing, I have to rewrite this whole thing."
The only difference is that Unity has to see the file before it'll create a .meta file (and before it'll update the .csproj files to include the new file)
So if you create a script outside of Unity and don't let Unity reload (I have auto-reload disabled, for example), then there will be no .meta file yet, since Unity won't have imported the asset
I make all my scripts from vscode so I can use templates.
I have a plugin that creates the meta file for me too.
But it's not necessary. Only thing that matters is the csproj being updated (which the c# plugin does).
Because Unity auto compiles after each file is created so its a pain when I can do most of it in VS
Ah thats it, it didnt appear in VS if you didnt create it in Unity then.
I have auto reload I think, but I had an issue when creating file outside of Unity
People even recommended creating them via Unity here
Looking for some guidance on a problem I'm trying to solve. I have some Monobehavior that needs to be dynamically given "effects" at runtime. The effects change the behavior of either the monobehavior or something that interacts with it. The main way I have been doing this was to just use polymorphism for the effects. In other words, base class "Effect," so the monobehavior stores a list of those effects and then I can add whatever sub classes I want during run time. The effects themselves define behavior of the effect in code. This seems to lead to a large class hierarchy which I kind of want to avoid due to how brittle it is. Is there a better way to implement something like this? TLDR: I want to dynamically give different behaviors to a monobehavior at runtime and I'm wondering if there are simple options other than polymorphism. Should I just make the effects a data store and implement the behaviors as a set of switch statements (say) in whatever components actually use the behavior?
Composition
this sounds reasonable; perhaps you've just been combining things that shouldn't be combined?
can you give an example of part of the hierarchy you don't like?
ok let me see how to express this succinctly. this is a tile-based game. i have... things that can occupy tiles... let's call them terrain. the terrain imparts effects to the game. the effects that the terrain can have depend on the rest of the environment. so the idea was to have an "effects" class for the terrain and add/remove these effects from the terrain Monobehavior as the environment changes.
one example effect is modifying movement of the players' units. another is damaging them. another affects how the player's units can, themselves, affect the terrain.
the goal is to have a lot of different effects. i haven't really built these all out yet but i can see issues with overlapping functionality and whatnot. so i guess my question is, is this just a difficult problem that can be solved reasonably with polymorphism or is there an approach that is more amenable to the situation...
The premise sounds fine to me.
ok thanks for your input.
One way I've handled this before was to give the effect class a bunch of virtual methods that all do nothing
so there's one for OnUnitEnter that you call whenever a unit enters the terrain tile
and the abstract base class's method is empty
another might be ModifyMovementCost(int currentCost)
the base class's method would just return currentCost
Technically you are doing some polymorphic calls since I assume these effects take in a player ref
you iterate over all of your effects and run the relevant method
most of them will do nothing; a few might actually have an effect
The other way would be to add interfaces for each kind of effect
not literally every concrete effect
but the more abstract ideas like "an effect that can apply to a unit"
so i guess... the idea is that the abstract base class defines the list of possible things that can happen, and the child class determines whether the effects actually happen and what they do
or maybe "an effect that applies to a unit when you enter the tile"
I have a very tile-based game. I use ClassTypeReferences to tie the definition of a specific class to an SO. Each tile’s TileBase is tied to an SO with that classtypereference. Different things in code can instance the relevant class to use the code on command.
Then you'd be filtering your big list of effects by type
Yeah, my abilities class has like 5 lists and it checks if they are empty or not, but each list can contain similar behaviours.
foreach (var effect in effects) {
if (effect is IOnUnitEnterTile enterTileEffect) {
enterTileEffect.Apply(unit);
}
}
My tile SO can also have a prefab tied to it if I need something more involved
This one wouldn't be specific enough by itself.
since there are multiple situations where you apply an effect to a unit
if I use ClassTypeReferences, I make sure to restrict it to classes that implement a specific interface or abstract base class
One solution would be to store a separate list of effects for each situation where you use effects
like my SOs have a few class type reference fields for: ICustomDraw, ConductivityStrategy, and TileMonobehaviour
List<IUnitEffect> onEnterTile;
List<IUnitEffect> onExitTile;
e.g.
This is less convenient than just having a single list of all effects that currently apply to the tile.
Targeting parameters seem pretty common to split with behaviors
in this case, you can have a ClassTypeReference to a type that is constrained to either implement ITileEffect interface or extend TileEffect abstract base class.
yeah, since "damage unit", "heal unit", and "give unit a bonus" are all things that need a Unit
so an interface makes sense there
all of these kinds of effects share a requirement to be given a unit
I would make an abstract base class for any sort of effect, and make many interfaces for different types of triggers
like ITileEffOnEnter, ITileEffOnLeave, ITileEffBombable, ITileEffBurnable, ITileEffConductive….
or whatever
That's kinda what Ive came to the conclusion of when brainstorming these roguelite games
then you have a reference to the one type for the type in an SO, and check if the type implenents a given interface
ok so i guess what i'm hearing is... it's ok to have one or more collections of effects that specify functionality in code (whether by being child classes or by being interfaces), and just have clearly defined categories of uses for the effects so you can call them as appropriate in your monobehavior.
if a tile effect needs any sort of connection between the different behaviours, then it should be one class for a tile with multiple interfaces, so they can cross talk.
TriggerOverTime, TriggerOnHit, TriggerWhenHit
if the behaviour is super separate (like in my case, ingame behaviour separate from level editor behaviour), then they should be split
but generally yes
i strongly recommend using ClassTypeReferences plugin for this, and also making a giant dictionary that links every tile to an SO with actual info
Dictionary<TileBase, MySo> is basically mandatory
then you can do whatever the fuck you want in the SO to connect game logic
i'm not sure what you mean by that. can you explain further?
set booleans, enums, class references, etc
Tilemap lets you use GetTile to query what tile is at a given coordinate
I do something similar, except that it's Resources-based.
when you know you interact with a tile a given coordinate, GetTile gives you a TileBase, which you now need to go get the actual game logic for
In my case, I have a bunch of classes that derive from Module that add features to my Entities
For each class, I create a scriptable object asset (ModuleInfo) that lives in a Resources folder
It contains things like localized string references
you want a giant Dictionary so you can go from TileBase to a permanent asset on disk that tells you wtf the tile does. In this case, a scriptable object
why not just store the SO as a reference in the tile?
I use the dictionary approach elsewhere, like to look up SO assets by a GUID I've attached to them
you're associating something with each kind of tile
or module, or whatever
SO has a reference to the tile in it. But If I call Tilemap.GetTile, how do I get the SO?
need a dictionary
in my case, I could add an instance field to Module that holds a ModuleInfo reference
but then I'd have to manually assign that for every instance
The association isn't per-instance. It's per-type
So it doesn't make sense to use an instance field.
hmm... in my case, the tile types are constructed dynamically based on environment.
yeah, you want to have a separate connection of instance-data, and one big dictionary that makes it easy to query just the base data
the set of effects are combinations of things based on the environment
i gtg, but fen has u covered
thanks
Although, it sounds like Loup was describing per-instance information there.
i.e. associating a scriptable object asset with each individual tile
and in this situation, I don't think you'd be referencing assets at all
dictionary sounds fine
each tile should just have a list of effects on it, and each effect should have its own configuration in it
this sounds the most straightforward to me tbh...
a DamageUnitsWhoEnterThisTile effect contains the amount of damage to do; it can stand on its own
i kind of already have the infrastructure for this so... i think i'm going to just do this
You just need to decide between:
- Every Effect has a crapload of do-nothing methods on it and overrides just a couple of them
- Effects implement various interfaces, and you filter your effects based on those interfaces
for the latter, you could do something a little interesting
public class HurtUnitsWhoEnterMe : Effect, IUnitEffect, IOnEnterTileEffect
IOnEnterTileEffect could be a completely empty interface
foreach (var effect in effects) {
if (effect is IOnEnterTileEffect && effect is IUnitEffect unitEffect) {
unitEffect.ApplyToUnit(unit);
}
}
IOnEnterTileEffect doesn't actually specify any behavior at all. It's just a label.
hmm... interesting
IUnitEffect does specify behavior
I always feel weird when I'm manually filtering types like this
Instead of these "tag" interfaces, you could just have a way to ask an effect if it applies in a certain situation
where "situation" is an enum or something
sorry to those of you already in the know. but I just realized you can inline assignment in c#. 😅
so you can write this, as opposed to that. works for function calls to.
it's only a syntax thing, but figured I'd share for those of you that are like me and prefer to get rid of that extra line of code 😄
right... that makes sense as well...
I'm more of a stick to a single class and declare everything but check at runtime via enum (or instantiate the lists of behaviors and who cares if they are populated or not)
oh yeah, = returns the assigned value or reference
which usually just causes confusion when people use it instead of ==
compiler warning for every time you discard the value returned by =
⚠️ 9999
anyway thanks a lot for your help guys this stuff is currently implemented in a very ad hoc manner which has hampered my ability to extend it, you've given me some great ideas for how to systematize "effects"
every time i arrive at a new problem to solve or feature to implement, i think implementing that will be relatively easy but... then i sit down and think about it and it really requires a lot of time
an effect system is like
two steps away from a programming language
The closer you get to implementing an entire programming language, the harder it becomes
funny
At some point you just cut your losses and implement some things in C#.
Your "Effect" class just has a text field and a runtime compiler. No interfaces, no hierarchy. Just create new SOs for each effect and give it a name and a string parameter, into which you type your effect code.
I actually briefly considered doing that until I realized that debugging this would probably majorly suck.
Though I feel like large devs actually do this with scripting (e.g., LUA) and whatnot.
I mean it's a nice way to decouple gameplay design logic from core gameplay logic.
but the infrastructure required for a small project is too high of a cost.
basically, even with the extremely frictionless nature of the C#/VS environment, this project still takes tons of time, so downgrading to whatever would be required for scripting would result in a significant slowdown.
anyone have any idea of what is the best way to pull off something like this when the camera is looking at the body/gun. I was thinking of having a square collider coming out of the head that shows where the player is looking at and checking if its looking at a gun collier. 10 mins into itegrating it i realised how uterly retar*** my method was and i currently dont have any other ideas
and follow up question. Is it possible to have two "OnTriggerStay" methods for two colliders in the same class
No
One method with the same name and signature per class
You can validate the collider type INSIDE the same OnTriggerStay, and simply do different things depending on the collider
OnTrigger* methods don't tell you which of your colliders caused the message to be sent.
If you want multiple distinct colliders, you need to put them on different objects
You can check the SHAPE if they are different.
Or check some parameter of the collider (like if one has a high radius and the other is small)
It is unweildy though
I agree that separate objects is generally the best way to go though
That's what I do
hello, any suggestion for a lite version of unity ? I dont want to really make a full game but to test some code on an objects with physics properties and such stuff
I guess 2019 version is a bit smaller...
Other than that, not really
alright thank u
Godot but Unity be like:
Are these errors really that important, because the code works fine?
This is a problem with the inspector.
I'll sometimes see then when I undo or destroy things.
is there a way to bypass it?
it's usually solved by restarting the editor
assuming it's spamming the error constantly
yup
good to know that
In general, if you look at the stack trace and see no actual line numbers, it's the editor being fucky and a quick restart will at least supress it for a while
yeah I just restarted it and now its not showing anymore, so that will do it for now
thanks yall
How can I get the sizes of a sprite in a script?
Like the dimensions of the texture itself?
yes
can someone please help me i want to make an object appear in unity in a 2d game when i hold down s and when i release it it disappears again
thats my script (it does not work)
using UnityEngine;
public class ShowOnKeyPress : MonoBehaviour
{
public GameObject objectToShow;
void Update()
{
if (Input.GetKey(KeyCode.S))
{
if (objectToShow != null && !objectToShow.activeSelf)
objectToShow.SetActive(true);
}
else
{
if (objectToShow != null && objectToShow.activeSelf)
objectToShow.SetActive(false);
}
}
}
size (width and height) (vector2)
If this is the only thing controlling whether or not the object is active, just check if the object isn't null in Awake() instead of in Update(). ie - your code could be a lot simpler if it looked like:
public class ShowOnKeyPress : MonoBehaviour
{
public GameObject objectToShow;
private void Awake()
{
if (objectToShow == null)
{
// log a warning here or whatever
}
}
private void Update()
{
objectToShow.setActive(Input.GetKey(KeyCode.S));
}
}
also activeSelf means "is this exact gameobject active" which is different than activeInHierarchy (since a parent could be inactive)
i found the problem i apply the script that i want to appear with s and then the script disable it self when i start the game
but thx for our help
i had another problem how can i cut the yellow circle at the blue line i want to make a car headlight
with a Mask or SpriteMask component
I'm not sure if this is possible but you might want to look into the "max size" property here https://docs.unity3d.com/560/Documentation/Manual/class-TextureImporter.html
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
I have an assigned sprite variable and I need to reach its sizes (width, height or vector2). I have nothing to do with texture. So I cannot reach maxSize
I throw this sprite into sprite renderer
thx
I'm not sure why you said yes when I asked if you were talking about the dimensions of the texture, but you're talking about the scale on the transform component.
In a script, you can modify the scale of a sprite by using gameObj.scale
I'm not talking about scale. I need to reach the size of my sprite. for example, if the sprite is 300x300 in size, i need to reach it in the script. I am writing with translation. so i may not be able to explain or understand this right now.
it could be
I need to know what you're talking about before I can help you
You should do some research on unity lingo
what do I need to write to get the sizes of this sprite?
Go into your transform component on your object and look at the scale. Play around with that and tell me if that's what you're talking about first
Are you asking what the apparent size (in world units) of a Sprite would be if you put it into a SpriteRenderer that had a default scale?
Or do you want the actual resolution of the image?
Depends what you mean by "size"
width and height in world coords?
everybody is saying there's a bunch of different notions of size for a sprite because there's the underlying image which has a resolution in pixels and then the sprite also has a world size which is related but also different than the resolution of the image
That doesn't answer my question.
I need to know exactly what you are looking for
Do you care how many pixels are in the sprite?
Or do you care how big it will look in a SpriteRenderer?
yes, for its size in the game. Since I am assigning it to a sprite renderer component, I need to get its size
spriterender has a bounds property
Any ideas for this?
the code is empty
Imagine it
I'm trying to make a game that uses a hexabody like character controller similar to the one so see in boneworks, i cant seem to get the hands how i want them though, they are always to springy and since part of the game will have you use your hands to walk (unoriginal trust me i know) this will make it really difficult to move around, maybe ill add this springy hand feature as a weapon of some kind but for now it would be nice if they were more rigid.
ive tried maxxing out the spring values but it didint seem to help to much
nvm
turns out the sping being high was the issue
wtf this is so weird
what
Oh yeah the hastebin link must have expire, I’ll edit with a working link soon
Hey, can someone help me, im working with the a* Pathfinding assets, and for some reason the seeker just always seems to pick a way through obstacles, any ideas?
don't crosspost
What else am i supposed to do if no one responds?
yup. its also difficult to help on a specific asset especially if you don't explain any of the setup.
loving this debugger deadlock
Unity in a nutshell:
It seems to be a feature 😅
what helps for me is enabling debugging mode in editor first then enable the attach unity
ok Ill give it a try
you know the saying, "it's a feature not a bug"
just to be clear talking about this one
Is using addressable assets really worth it? It seems like you can't mix "normal" assets with addressable assets, so that means you have to create a wrapper for any assets from the asset store right?
What is a "normal" asset as opposed to an addessable asset?
Addressables just create an address for assets so you can load them from that
Either way, definitely a question for #📦┃addressables
Addressables give you different benefits in performance for example. Loading and unloading assets, batching, async handling
I see, I didn't realize there was a channel for addressables
If you directly reference an Addressable asset from a non-Addressable asset, you wind up with two copies of the asset
one in Addressable-land and one that isn't
@heady iris That seems problematic
I discovered this while I was trying to use Addressables to load all assets of a certain kind into a dictionary
(so that i could avoid manually referencing them or stuffing them into one giant Resources folder)
The really confusing part is that it works fine in the editor
It just fall apart in the build
Ah ok, I wasn't aware. I need to learn more about addressables before I try to answer anything about it then. Thank you
@heady iris isn't that what labels are for?
Asset Labels? I haven't messed with those, actually
@heady iris If you put a bunch of assets under the same label you can load all addressable assets that match the label.
Oh, you mean addressable labels. That’s what I was doing :p
But I needed references to the same objects that everyone else had
ahh
The addressable-loaded objects were unrelated to the directly-referenced objects
I'm still trying to wrap my head around the whole thing, but I understand bits of it
or at least I think I do
CanEditMultipleObject is no more, what's the new flag for that?
You have your parentheses wrong
The closing one belongs before the comma
Probably worth making less assumptions
jeez
thx
i didn't know you could pile up attributes like this
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hello people, I am new here so, hi.
I am having problems with this while loop that causes the entire unity engine to crash:
private void getNewPosHanger()
{
float posY = 4.5f;
bool isLooping = true;
while(isLooping)
{
float positionEnemySetX = Random.Range(minRangeEnemyHanger, maxRangeEnemyHanger);
if (!isRayCastPosFull(new Vector2(positionEnemySetX, posY)))
{
posNextHangerEnemy = new Vector2(positionEnemySetX, posY);
break;
}
}
}
This function allows me to get a new position for the next enemy on screen, but it checks if that new position is already taken by another foe (that's what the isRayCastPosFull does).
I call this function when the enemy is created an in the start of the gameobject so the next enemy already has their position.
Go through your code logically and look at the condition of the loop. When does isLooping get set to false?
If that break is never reached itll never exit
But the thing is that I want to look for a new position if that is already taken. If that position is already taken the while loop should repeat and find a new random position right?
any other ideas on how to implement that behaviour?
2d or 3d?
2d
🤷♂️ depends on the implementation of that method you're using. "Should" but doesnt. You might wanna use an overlap function instead
if 2d that this private void getNewPosHanger()
{
float posY = 4.5f;
bool isLooping = true;
while(isLooping)
{
float positionEnemySetX = Random.Range(minRangeEnemyHanger, maxRangeEnemyHanger);
if (!isRayCastPosFull(new Vector2(positionEnemySetX, posY)))
{
posNextHangerEnemy = new Vector2(positionEnemySetX, posY);
break;
}
}
}
something like this
And add a safety that breaks out of the loop if no valid positions have been found for like 1000 iterations!
this one is a good one? How can I get the count of the loops?
or maybe with a for loop
Count how many times its looped or use a for loop
eh yeah this is the code
You use a variable declared outside the loop, or a for loop. Either works
let me try that one
You should show what that method is doing also. It could be that you're simply returning true all the time so the break never happens
An also, test the method alone so you know it works before using it elsewhere
Yeah if it always returns true, either the ray is too long, hits something unexpected, or hits the same position every time (if your random min/max variables are identical)
I don't think it's the problem but you never know, it basically casts a circle in the given position
private bool isRayCastPosFull(Vector2 location)
{
RaycastHit2D ray = Physics2D.CircleCast(location, 1f, new Vector2(1, 0), layerEnemy);
if (ray.collider == null)
{
return false;
}
else
{
return true;
}
}
layerEnemy is a layer mask, correct? Not a single layer index
Add a debug, dont assume what it is doing. It's entirely possible the layer is setup wrong, that you have another object (the floor) on the wrong layer. Debug the name of what was hit
(also that big if statement can be simplified down to a single return ray.collider != null;)
Another thing I just noticed too is that you are doing a random selection for the X value until one is found. This means theres a very likely chance you are checking the same position over and over.
If you truly need a random place, i would increment x by some amount and check along the entire area. Then return a random index of the areas that were valid
This would save time in the case where only like 1/50 spots were valid
new info, the check is working just fine, but I will implement this idea, because right now it's looping for a long time a cannot find any avaliable position, even though there are some blank spaces
this idea
thank you all
guys https://youtu.be/CdPYlj5uZeI?t=784 this video mentions splitting the vector into two components. how does it do that? isnt dot product combining not taking apart?
A detailed look at how we made our custom raycast-based car physics in Unity for our game Very Very Valet - available for Nintendo Switch, PS5, and Steam.
BUY NOW!! https://toyful.games/vvv-buy
~ More from Toyful Games ~
- Physics Based Character Controller in Unity: https://youtu.be/qdskE8PJy6Q
- Instant "Game Feel" Tutorial: https://youtu.be/...
Probably worth noting where in the video you're talking about
i linked the part
if u press play it starts where im talking abt
The dot product is a scalar portion of vector projection
if im going to be honest we havent reached there in school, so its going in one ear and out the other. i guess what im trying to ask is how we are supposed to split it up
The result of those two dot products is the vector split up into two in the way they're talking about
which two dot products. didnt he say in the video we just start off with the orange vector
yes, and he shows two dot products
which are the blue and red right?
The (length of the) white arrows on those lines, yes
i guess what im asking is where u get those two lines. i thought the dot product was a combination of two things and in this video you only start off with one thing so i dont get how you split one thing into two
the direction the tyre faces and a perpendicular direction to that
presumably you have the rotation of the wheel, so you can easily get those vectors from that. If you have a transform you can just use transform.forward and transform.right if it's not being rotated around like the wheel visuals
like the steeringAngle?
the angle at which the wheel is turned
Sure. If you just have an angle then you can use Quaternion.AngleAxis and quaternion multiplication
neat video!
yeah so i have each of the directions, and i have the velocity of that orange arrow. and i have the directions of the blue and red arrows. my problem here is that i need the velocity of the red arrow in order to apply that same force as a centripital force
I don't know what you mean, the forward and right directions should be normalized when used in the dot product
and the result of the dot products with the velocity are the components they're talking about
i dont understand what this means. i was learning about the dot product but it never mentioned a result of two components only one
like without anything related to the dot product i have all three directions and the velocity of the orange arrow and im trying to find the velocity of the red arrow
Yo can I ask for help in scripting here?
float slidingComponent = Vector3.Dot(velocity, right);
float rollingComponent = Vector3.Dot(velocity, forward);
?
so you get the dot product of the velocity of the orange arrow and the right direction and then the same thing of the velocity and the forward direction?
Yes
Yo
In the #archived-code-general channel? Yes
I tried using WorldToScreenPoint on a GO but it always goes to the bottom left
I use a list and an index for the Transform
Gonna need a LOT more info to help. !code would be a good start
📃 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.
Ahh thanks
if(LockedOn)
{
lockOnGraphic.SetActive(true);
}
else
{
lockOnGraphic.SetActive(false);
}
enemyPos = GetComponent<TargetList>().Targets[tgtI].GetComponent<EnemyPosition>().enemyPosition;
lockOnGraphic.transform.position = camera.WorldToScreenPoint(enemyPos.position);
//This is the defenitions
public Transform enemyPos;
public bool LockedOn;
public GameObject lockOnGraphic;
@spring creek
enemyPosition gets the transform of the enemy GO
Debug the values of enemyPos
You are using a screen position as a world position
it's a public so i can see it in inspector
oh wait
nvm
Have any ways for me to change this?
There are ways to set a recttransform's screen space position (assuming that lockGraphic has a recttransform).
I dont remember how though
yeah lockOnGraphic is a parent of an image and one slider
This utility class might be of use here https://docs.unity3d.com/ScriptReference/RectTransformUtility.html
what i've also noticed is that this code worked perfectly before
and when i used a list getting automatic values it got bugs like that
//List class
public class TargetList : MonoBehaviour
{
public List<GameObject> Targets = new List<GameObject>();
public int targets;
// Start is called before the first frame update
void Start()
{
if(GameObject.FindGameObjectsWithTag("GiodEBody") != null)
{
Targets.AddRange(GameObject.FindGameObjectsWithTag("GiodEBody"));
}
if(GameObject.FindGameObjectsWithTag("EnemyTurret") != null)
{
Targets.AddRange(GameObject.FindGameObjectsWithTag("EnemyTurret"));
}
}
// Update is called once per frame
void Update()
{
Targets.RemoveAll(s => s == null);
targets = Targets.Count - 1;
if(Targets.Count == 0)
{
targets = 0;
}
}
}
if Targets.Count is 0, targets will be -1.
If I have a vector that is: (-0.6401844024658203, -0, -0.7682212591171265) would the perpendicular vector be (0.7682212591171265, -0, -0.6401844024658203)?
wait so i do a vector and a normalized direction
for my dot product?
the velocity is not normalized, the directions should be
for the velocity part can i plug in just the vector
cause isnt velocity direction and magnitude like a vector
I don't know what you mean, the velocity is a vector that has a magnitude that is the speed
ok yeah thats what i was asking. so i just dot the orange vector in the video with the normalized direction of the red right?
Yes
and that returns the blue vector with its magnitude and and direction?
or wait.
No, it returns a magnitude
oh a magnitude of the red?
kk and the magnitude of the red and blue arrows are the same
jeez vectors are interesting
will i learn this in AP physics? 😭


