#archived-code-general
1 messages · Page 287 of 1
oooh ty
The 2 common ways AI is done for games is FSM (Finite State Machines) and BT (Behavior Trees) - FSM is running a single state at a time, for simple AI (like companions, vehicles, Mario-like enemies, etc) this works fine, but when AI need to manage multiple states and complex transitions a BT is more flexible (and also more complicated to implement), in addition to those, AI can also have many "layers" such as pathfinding, obstacle avoidance, flocking logic, "assistance"/aggro (for example: player attacks 1 AI, and 3 nearby AI also respond), goal-oriented/look-ahead, score based (which is how Sims AI decide what to do), weighted decision making (such as Dark Souls), and many other forms ontop of the FMS/BT, there are even Hivemind AI (often used in RTS where you have a lot of AI controlled by 1 system performing their CPU-intensive logic), and threaded simulations (such as how GTA can have activities go on in scenes that arent loaded), proximity and stats can also affect the logic (such as how close to "see" a player, how loud to "hear" a sound, how "accurate" to shoot a gun, etc)
It certainly is a massive topic and there are some GDC talks about specific games taking specific AI approaches such as Sims, Watch Dogs, Assasins Creed, GTA and others, "Game Makers Tool Kit" on YouTube also have lots of video essays about AI design - it just depends how complex of an AI you want to build, and how relevant AI is to your gameplay, I think starting with FSM is certainly the most "simplest" form of AI though, but I donno the scale of your game

Can I chat with you in DMS to share more
Behavior trees sound good
But AI can also have many "layers" such as pathfinding, obstacle avoidance, flocking logic, "assistance"/aggro (for example: player attacks 1 AI, and 3 nearby AI also respond), is what Im aiming for
Ready Or Not style AI
And I have 8 days for the deadline
publisher request

You can start a thread, maybe others can chime in, im not the best with AI, as most of my projects have never been large enough to need anything more complicated than a FSM with a few "layers" ontop, theres just so much complexity AI can take its a pretty big topic, im not really sure if a complicated system can be built, tested, iterated and scaled within 8 days, though if you have a lot of experience, you could maybe setup a BT in a day or 2, ive seen a UIToolkit tutorial on making a editor for a BT, though havnt attempted it in a practical/commercial project myself
Ah, it was just it was a actual game on Steam and I didnt want to sound self promoting 
I know the goal of the AI cant be completed in 8 days obv, but Im trying to research (currently watching Game Makers Toolkit ;3) the most obvious parts AI development to make them the best I can
I've been poking around in the depths of the AI Mines for a while
Ah, so you have an already-released game with a 8-day deadline to update it with a BT-like AI system? (I dont think thatd be self promoting to talk about it in that way)
Its not released yet, and I didnt mean to sound like it was my project, I work just for the studio as a developer
It currently has a AI system but its not the games style
the simplest thing you can do here is to add more randomness
if you're concerned about making them feel smarter, then a whizz-bang-fancy AI system may still feel very flat
you mostly just need to make the player think the enemy is smart (:
Thats what Im learning from the channel Ive been recommended
F.E.A.R.'s enemies are constantly yammering
These are the notes im taking lmao
- AI should hold their ground more, instead letting the player come to them```
its only been 2 minutes
"yammering" reminds me of how the Batman style and Hitman AI work based on your progress and positioning, like if you recently been spotted or attacked someone how they "permanently" change how they move, act and talk
I'm developing a survival horror-y game right now
Thats what I want lol, the AI to be more "dumb" when they know nothing
same bro
I've implemented GOAP and a complex perception system, but I still need to convey to the player that there's complicated stuff going on :p
it's an interesting problem
a lot of this is more for my own curiosity's sake
this has absolutely not been the most efficient way to implement a game
Hello. i have real camera, which provide SDK (.NET), how can i add it to Unity? if it is possible?
Much delayed, but FWIW, moving to a separate folder outside of assets and using "Add as Link..." worked, so I'll probably just do tests like that rather than use the UnityEngine unit tests framework, at least for things that are completely independent of the game.
I'm trying to read the documentation here about using InterestGroups, but when I type out VoiceConnection.Client.OpChangeGroups, there is no such thing even though I put all the 'usings' at the top.
Hey guys, can anyone see if they know something about this that i have asked?
You can create it at runtime, but it's gonna be a huge waste of resources if you do that every frame.
I could still use some help with this ^
Hi guys, i Have a problem the OnDrop() func, im trying to make a little tower defense in 2D for learn Unity, but impossible to catch this func on my plots where i want to build a turret.
I made a post in the forum : https://forum.unity.com/threads/problem-with-ondrop-for-a-tower-defense-2d.1557701/
you failed to implement the IDropHandler interface
Ty for your reply, yeah i changed that after my post, but that had not fixed the problem 😦
you will also need:
- A PhysicsRaycaster2D on the camera
- An Event System in the scene
and of course - to have already started a drag operation from elsewhere
Oh, i don't have a PhysicsRaycaster2D on my cam. The drag works very well with mu turret component, just the plot doesn't detect the onDrop(). thanks 🙂
The PhysicsRaycaster2D on the camera fixed the problem, thank you so much 😭
is there anyway i can just take a print of the camera and display on rawimage?
That's what the render texture is for. You basically render the camera view to a render texture and can use it however you like.
Can you take a screenshot of the photo cam preview?
sure the character spawns there in real time btw 1 min
did you try to add the line: renderTexture.Create(); that I linked?
is working xD i just did shit with the positions ahah
thanks dlich ahah too many hours awake
Ok, that's good. For future reference, I meant the preview of the camera. If you select it, there should be a small window showing what the camera sees.
From reading the docs, this doesn't seem to be necessary if you're rendering to it from a camera, as assigning it to a camera does the same thing.
IEnumerator Upload()
{
commandField.text = " ";
text.text = "COOKING UP A RESPONSE...";
using (UnityWebRequest www = UnityWebRequest.Post("http://xxxx/help/" + commandField.text, new WWWForm()))
{
yield return www.SendWebRequest();
Debug.Log("Complete!");
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError(www.error);
text.text = "ERROR: " + www.error;
}
else
{
text.text = www.downloadHandler.text;
}
}
}
I wanted to send a post request using the unitywebrequest, I've tested my API on postman and it works fine but when bringing it into unity it only gives the error "HTTP:/1.1 404 not found"
The post request queries a backend server, a valid query would look something like "http://xxxx/help/how+would+I+undo+an+action+in+the+editor"
I enabled allow downloads over http but it still gives this error

oh
You're setting commandField.text to " "?
oh i found out why
yep I just realised 
it is solved 🎊
I have this discrepency between the built version and editor.
I was making a grid for my game using a quad and material; In the editor the grid is the correct size but in the built version the grid is much bigger and becomes misaligned
How are you rendering it?
The grid is a physical object in the world
oh wait nvm
i attached it to canvas 😨
no wonder the transform kept adjusting
{
};```
I would like to know if it would be possible to unassign this specific event, or would I need to create an action in order to do so?
write the logic in a method or store it in a delegate then you can unsubscribe it
ah makes sense thank you
how do I prevent people from flying using objects that we can carry like in zelda?
object is also solid, and can reset isgrounded from player when on top(for gravity reset and jumping)
because objects do not make you fly by default, it is likely a result of constant depenetration, or by using built in physics and standing on an object with velocity
it is like, i can hold something and take it with me, but if i stand on the item while i am holding it, and I jump, I take it with me, but i am still on the item, and i fly indefinitely because I am still holding the item which prevents it from falling
was wondering what are ways to prevent it, I think it is a common bug/feature in a lot of games
Smol Unity Rant:
You know what really grinds my gears? The fact that Monobehaviour implements "OnDrawGizmos", which is a method that is only used for the Editor. Therefore any builds that have "OnDrawGizmos" will crash unless you manually ignore that method for all Monobehaviours
anyway around this ?
use the #if unity editor stuff no?
this kind of thing not work?
well yes i understood that part, but what i said still applies. flying on objects is due to something that i wrote above, so you must figure out what the cause is. The solution could be something as simple as checking how you are moving these flying objects and to not move them into other objects. Cast and check what is in the way
ah okok 
Wdym crash? I don't think anything would crash. The method is just ignored in the build.
DrawGizmoAttribute
toasted cheese sandwich
OnDrawGizmos isn't ignored in the build, maybe with that attribute, but to have to implement that attribute is just silly as the gizmos are only ever for the editor
No. I don't think you need the attribute.
And the method is ignored as in isn't called in the build
I doubt it is ever called in builds. The attribute solves your problem completely, just look at the docs instead of being a prick, and you can easily exclude the code with preprocessor ifs
damn im a prick now sheesh mr mod , cool thanks will look into this more
What makes you think it's called in the build? Did you actually test it?
yup but think i may of just found a work around
How did you test?
Can you provide any proofs? Because it sounds unreasonable.
does anyone know how to store 2d grid position into a variable and and see what type of grid position such as (0 = floor & 1 = wall & 2 = win)?
i can share proofs just don't know if ill be breaching contracts , thanks for all the feedback guys i have a different method @quartz folio apologies if i came across as a prickle , all love from myside .🤘
A 2d array of tiles ot something..?
yes 2d array tiles
i've making a ai rat maze, i've already set up the movement, no collisions are used, i used to check what's grid is Infront and other sides of the rat. the problem i have right now is that i will keep going to area's that has been explored and not going towards unexplored area's such as intersections where rat has to go front or right, position which i want to make sure i has a memory array's of which grid it had already explored and what grid hasn't.
your algorithm is incorrect not the grid setup
why is it not correct?
you mean your mouse will stuck in explored area not going to new area, i guess some checking in your visited[] is incorrect
or you want this
https://en.wikipedia.org/wiki/Hamiltonian_path
In the mathematical field of graph theory, a Hamiltonian path (or traceable path) is a path in an undirected or directed graph that visits each vertex exactly once. A Hamiltonian cycle (or Hamiltonian circuit) is a cycle that visits each vertex exactly once. A Hamiltonian path that starts and ends at adjacent vertices can be completed by adding ...
oh yes, I will add in a validation that if there is an only explored areas, then it can go to that until it finds an intersection that it can randomly choose if it wants to go what ever way until it finds an unexplored area where it will need.
also i will have a look at this link, thank you.
what do you think about this
How do you guys usually performs your checks on your game's performance and stability?
i believe there are several algorithms known to find hamiltonian paths.
i don’t remember if it is NP or what. It’s been too many years
But it is a common problem
spam a ton of crap in your game, then playtest your map which has a ton of things going on
profiler helps find specific methods that might be particularly bad.
in my case, i had very fancy RuleTiles which made RefreshTiles() consume 2/3 of the time of my level loading
solution: optimize usage of RefreshTiles
during play, all the time cost in my game is pretty evenly distributed across different responsibilities. => no clear thing that really needs optimizing
profiler also lets you look at lag spikes, which are spots where you want to pay attention because usually that is caused by one specific thing
I can think of several ways to do this, ranging from simply iterating over the list and moving around the entries, or having a second list that is used as a resorting buffer, but what is the best practice, if I want to take a List, and insert a value into the middle of it, and also displace all other entries, such that they move up in the index?
Example:
List:
0 Sword
1 Shield
2 Bow
I then attempt to insert an arrow into the list, at index 1, and displace everything after it, like so;
0 Sword
1 Arrow
2 Shield
3 Bow
I'm working on my inventory system, and I want a drag and drop functionality that can allow me to drag an item into the list, displacing all the other items to make room for it.
On that same note, what is the best practice for removing an item from a list, then "collapsing" the unneeded index?
I take this list:
0 Sword
1 Arrow
2 Shield
3 Bow
and then I try to remove the item in index 2, the other items "sliding back" in the order
Like so:
0 Sword
1 Arrow
2 Bow
That is standard functionality of the List class
I thought List.Insert overwrote the index?
All the documentation I found says it does.
And google says I need to make an entirely new list every time I do that
So Insert will indeed displace everything else in the list, rather than just overwriting what's in a particular index? and List.RemoveAt doesn't leave an empty index slot behind afterwards?
correct
Thank you very much. I know it's a silly question, but when I teach myself entirely using google... Well, sometimes that doesn't work.
if in doubt about C# the MS docs are where you should be looking not random shit on Google
Yeah all of this is explained in the MS docs
I think he may have confused List with Array looking at his questions
code
Why Object.GetInstanceID() is not thread-safe? It's just an integer read...
if it was 'just' an integer read it would be a property not a method
[SecuritySafeCritical]
public int GetInstanceID()
{
EnsureRunningOnMainThread();
return m_InstanceID;
}
it is indeed just spitting out a field
Of course, it's possible that another thread could be trying to modify that field at the same time
The field is initialized during construction and never touched AFAIK
Documentation says it doesn't change
Hey I got a question about perling noise. I want to create a map where its split up in x areas wide and y areas height.
For areas I mean stuff like ocean, Land stuff like that.
I cant figure out how to make this happen. When I play with noise values it either becoems super high or super low. No more natural flow
Does anyone know how to make that work with perlin noise
can you elaborate on what you mean by "super high" and "super low"?
yes one second.
This is how it normally looks like
This is the result with multiple diffrent tries
Like adding a depth offset, clamping the values between ranges
A layer of noise is not the same as a octave right?
no, an octave is a noise layer, but a noise layer is not always an octave. (when talking about procedural generation)
aah okay
but looking at the images I'm not 100% what it is you are trying to do
so what I probally want is a general noise layer. Then a noise layer dependant on what I want to achieve in that area
yes
It;'s possible you're sampling at integer gridpoints in the noise function and getting the same value everywhere, which is a known property of perlin noise
uhhh basicly trying to procedurally create a world. Where I can add requirements. Like 35% land and 65% water. And so that there will always be a big enough island generated
The gren squares are basicly the land areas
But thanks I'll try and take a look at that
Yeah I am still pretty new to it and while I did watch some videos and read some tutorials its still a little mystery to me haha
hello does any one knows where and who toask how to make an ui menu for phones i needed some help cause i'm new at making a game also new on the server
I've got several points in space. They are variable in position and amount. How could I draw the area between them on Gizmos?
For example, I can make an object that's a child of this script's, and it would add that object's position to a list
I want to be able to draw the area between all of them
is this going to be a 2D polygon or a 3D polyhedron?
2d polygon
Deciding what area is "inside" a set of points isn't trivial. It'll be easier if you only need a convex hull, though
I'm not sure what you'd use to actually fill in the area, though
All I want to do is in a sense connect the points, on Gizmos, and I think that would be enough. I'll try handling the area later. For now that is what I need
Cause if I do that, I think a gizmos line could work as a trigger of sort, right?
And for a non teleporting object, I wouldn't need to use math
Hey, quick question, is there a way to make the script automatically swap out the scriptable object attached to it?
I'm about to make another scriptable object for the script in question and I'd like to know if there's a function I can do that will swap them automatically.
wdym by "swap them out"
Depends. When should this occur?
I am using scriptable objects for my boss data, and I'd like them to swap the attached object to another one when the current boss is defeated.
Why not just have an array and reference the next index?
When you say "attached" I guess you mean "referenced"?
yes you can use = to reassign your reference to another object
I persevered and finally got it working. The solution from the uni was correct for me and it doesn't seem to miss at any point.
private void RotateToShootPlayer()
{
// Rotate tank in direction of player
var direction = transform.position - player.transform.position;
var angle = Mathf.Atan2(direction.x, -direction.y) * Mathf.Rad2Deg;
barrel.rotation = Quaternion.Euler(Vector3.forward * angle);
// Offset rotation to intersection point
var o = Vector3.Dot(player.velocity, barrel.right);
if (Mathf.Abs(o) < bullet.force)
{
angle = Mathf.Asin(o / bullet.force) * Mathf.Rad2Deg;
}
barrel.Rotate(Vector3.back, angle);
}
This is the solution. This script rotates the tank barrel and when I instantiate the bullet it is spawned with the barrels rotation and shoots forward.
nice that you got it working sufficiently - though I still think you'll see it's not quite right if you slow the bullet down a bit and compare the difference between, say, the player running away at a 50 degree angle and running towards the cannon with a 50 degree angle
I assume this would require a new function in my script?
Isn't your Atan2 incorrect/backwards? Usually it's (y, x). Maybe that's why you have to negate the y?
No using the = operator doesn't require a new function necessarily
This is all kind of vague/abstract without seeing your code
Okay, here is my code so far: https://hatebin.com/yjeeqzfbzg
you would just do bossData = whateverNewBossDataYouWant; wherever and henever you want/need to change it
Okay, sounds good.
No it doesn’t work if I do it the other way around. Even when I don’t negate the y
I mean it hasn’t missed a single shot yet and I’ve been messing with the speeds of both the player and bullet
sounds like your code or your objects are oriented strangely in the editor or something
Or your mental model of things
I chose to use the Y axis as the axis at which the bullet fires from
So the y axis is always pointing towards the player
Pretty sure I see your problem. Your direction is calculated backwards too
that's why you have a weird/backwards atan
I would expect e.g.:
var direction = player.transform.position - transform.position;
barrel.up = direction;```
(you don't actually need to do the trig at all)
but your current direction is backwards - it's FROM the player TO the object this script is on
The direction vector from A to B is calculated as B - A
How can i keep track of what scene i m in?
For example if the scene 2 is loaded something happens.
The simplest way is to put an object in scene 2 with a script on it that does something in Start
a ok thanks
So, I have a problem. I've got the attacking stuff figured out, but when I go into the battle screen, the player suddenly always starts at 0 HP. Here is my script currently: https://hatebin.com/onqsiceisa
The last thing I remember adding before this started was the playerHeal thing in Update.
I tried removing playerHeal from update and the same thing happens. Does anyone have any idea what's going on?
Start debugging your code
i tried that and i didn t worked quiet well in my situation. Do you know another way?
I learnt roblox coding during lockdown for 2 years, and I have grown up and roblox is out my interest however coding still is, I learnt coding with the Roblox LUA Documentation however I cant find a documentation for unity step by step from start to finish
Found a way to fix it.
there are beginner c# courses pinned in #💻┃code-beginner and the pathways on the unity !learn site are a good next step to learn the engine
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
what's wrong with what you tried?
So I made a save and load system. When I went into another scene, the x,z, and y loads from the first scene and I m falling infinitely. So I was thinking of checking whic scene is loaded and making a load file for every scene. I know it sounds stupid but I can t think of something else.
You'd have to explain what you're trying to do
"A save load system" is very vague
what exactly are you trying to save and load
and why would you need a separate file for each scene
so if i save the x,y,z from the first scene. When i enter the second scene the game loads with x,z,y from the first scene
What does "x,y,z from the first scene" mean?
and the x,z,y aren t the good ones
XYZ of WHAT
of the player
yes
All you need to do is capture the actual data you want to save in an object in an understandable way
Is the player a DDOL?
I need help understanding how a game mechanic works, however it seems difficult to describe. Is it fine to send a Itch io game with the mechanic or is that against the rules?
i mean actually it is
For example:
public class PlayerData {
public int currentLevel;
public Vector3 position;
}
public class SaveGameData {
public PlayerData playerData;
}```
If the current level is not the level the player was on, you'd not use the position from the save data here, you'd just use the level's default spawn position @unique delta
It's not against the rules but also you probably won't find anyone who's willing to go play a different game to answer a question
So then you're storing the player's position manually and loading it between scenes? Why save bad data?
yes
If you don't want to save the player's position, why are you saving the player's position
Maybe try your best to explain it with words first, and/or find a video showing it
The Player is able to hold space, depending on how long you hold space the jump is less or greater. Finally while holding space, you can hold another key for left or right, and when you let go of space it will launch you with the jumpForce accumalated and then left or right depending if you were trying to go those directions.
Here the player is holding right, so he will be launched diagonally right up
Ok so - when the space button is pressed set a bool to true and a timer to 0
Every frame add Time.deltaTime to the timer while that is true
Also while it's true, save a Vector2 indicating the held direction keys
When the button is released, take the accumulated time of the timer and the direction and add an impulse force to the player
You'll want to map the time held to a range of actual force values of course
that could be done with an AnimationCurve or just hardcoded with a Remap function
This helps, thank you!
Hi guys, I have a question about best practice.
I have a player and a liana who attack when the player collide with it. I have animation for Liana idle and when liana is attacking.
I have think about detecting the beginning of the attack animation for deal dmg, that's legit ?
Sounds like you may be describing animation events? Which allow you to execute logic on certain frames of an animation, such as your example: https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
void Update() {
spacePressed = Input.GetKey(KeyCode.Space);
spaceLetGo = Input.GetKeyUp(KeyCode.Space);
float moveInput = Input.GetAxisRaw("Horizontal");
if (spacePressed) {
timer = timer + Time.deltaTime;
}
if (spaceLetGo) {
rb.velocity = new Vector2(moveInput * timer, jumpForce * timer);
TimerZero();
}
}``` This code works, but how can I make the X axis be more strong? Currently the Player jumps in the direction of the Direction I want, but it is light. I want it to be a sort of straight diagonal jump that(The Way I am Holding(-1, or +1)) and to be more straight.
Oh yes sounds great, i'll check that, thanks 🙂
Multiply by value
If this is clearer, I want the player to go either straight up(0 Degrees up), or 45 degrees left or right up.
Oh, you didn't mean make it stronger
Well, you'd want to make if statements to check the X axis. If it's -1, angle is -45. 0, angle is 0. +1, +45
Angle should probably be a field
I found the issue*
It was the gravity. I just need it to be less when the player is launched. Thanks for the help!
🚬
!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 stumbled on a problem I can't seem to find a solution to. I have a player movement script that has wallrunning, dashing etc, but it doesn't work on moving platforms, the character just falls off. I tried parenting the moving platform or playing with the forces on the rigidbody but I couldn’t quite figure it out and I failed. Is there an easy solution to the problem? Here is the player movement code: https://gdl.space/vebuwufime.cs
ng
what?
Make the platform add its current velocity to the player's movement speed
OnCollisionStay, player speed += platform speed
Or just do it with any rigidbody so nothing would fall, not just the player
This is all theoretical though
I will try this
what?
I am making a projectile system for my moba game, similar to LoL. I use it for dashes, jumps, kb and skill shots. I have a a missile manager that on update moves all projectiles based on the data stored. Each projectile has point A (launch point) and point B (end point). Projectiles can fly in curves, arc and various forms. Upon building the system, I realised that I use rigibod body and collider to fire an event upon projectile hitting something. This is probably not very efficient. What is a good way to optimise it? (Later in the game, i will have walls that block projectiles or teleport projectiles or projectile hitting another projectile).
For something like a dungeon crawler with turn based combat. Would you have one state machine that includes all states or one for the gameplay outside of battle and one just for the battle?
I would probably have two separate state machines (at least)
Rigidbodies and the PhysX collision detection system are extremely efficient and likely more efficient than anything you would or could write by hand
hmm, okay, i read about some solutions with raycasting
but, it seems that it will be hard to implement with my feature requirment
you know raycasting is part of the physics engine too
why reimplement the wheel
well, it depends. need to do testing with 100-150 projectiles
Test it - I'm sure PhysX is going to be faster than your scripts
I use the following code to drag and drop rigidbodies, only thing is it breaks when I rotate the camera, it's in update so I'm not quite sure what I'm missing, thoughts?
private void Update() {
if (!_targetCamera)
return;
if (Input.GetMouseButtonDown(0)) {
// Check if we are hovering over Rigidbody, if so, select it
_selectedRigidbody = GetRigidbodyFromMouseClick();
}
if (Input.GetMouseButtonUp(0) && _selectedRigidbody) {
// Release selected Rigidbody if there any
_selectedRigidbody = null;
}
}
private void FixedUpdate() {
if (_selectedRigidbody) {
Vector3 mousePositionOffset =
_targetCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y,
_selectionDistance)) - _originalScreenTargetPosition;
_selectedRigidbody.velocity = (_originalRigidbodyPos - _selectedRigidbody.transform.position + new Vector3(
mousePositionOffset.x,
mousePositionOffset.z + RAISE_AMOUNT,
mousePositionOffset.y
)) * forceAmount * Time.deltaTime;
}
}
Rigidbody GetRigidbodyFromMouseClick() {
Debug.Log("handling");
var ray = _targetCamera.ScreenPointToRay(Input.mousePosition);
var hit = Physics.Raycast(ray, out var hitInfo, RAYCAST_MAX_DISTANCE, layerMask, RAYCAST_QUERY_TRIGGER_INTERACTION);
if (hit) {
if (hitInfo.collider.gameObject.GetComponent<Rigidbody>()) {
_selectionDistance = Vector3.Distance(ray.origin, hitInfo.point);
_originalScreenTargetPosition = _targetCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
Input.mousePosition.y, _selectionDistance));
_originalRigidbodyPos = hitInfo.collider.transform.position;
return hitInfo.collider.gameObject.GetComponent<Rigidbody>();
}
}
return null;
}```
in what way does it "break"?
It just drags in the wrong axis
So lets say I don't rotate the camera it works perfectly
But then it seems like it still moves in the same axises(?) even tho the camera is rotated
I think it's cause GetRigidbodyFromMouseClick, only happens once? (possibly)
Yeah, since you're remembering its original screen position. Moving the camera changes the object's screen position
oh, that's actually a world position
you should name that variable something more descriptive :p
My first guess for this problem would be to compare the current screen position of the object to the current screen position of the mouse
and to compute a velocity vector based on that
Yeah, maybe I need to rework the whole thing
It's some old code from another project I prolly found somewhere I assume
I mean it's kinda what happens in FixedUpdate I think
Have to go though, will keep at it a bit later
btw, if you want to drag something around on a constant Y-level, consider using Plane and Plane.Raycast
you can create a plane that goes through the object's position and with a normal that points up
then raycast onto that plane to get a world position based on a screen position
Is a null value in a function the same as not passing a value to that function, for the purpose of Overrides?
I.E
public void AddItem(ItemObject _item)
{
//Blah Blah Blah
}
public void AddItem(ItemObject _item, int _slot)
{
//Blah Blah Blah
}
Let's say this function, and it's override, are called by dragging something into your inventory.
If it is dragged onto a slot, it sets the slot variable. But if it isn't hovering over a specific slot in the inventory, the slot would be null.
In that situation, is
AddItem(Item, Null)
the same as
AddItem(Item)
?
in this case, null is incompatible with the int type, so that'd be a compile error
more generally, no, they are not the same
So basically, in the drag and drop system itself, I have to add null handling to choose between the two functions.
And only pass a value if one exists.
Thank you very much, I don't know if this was a dumb question or not, but I wasn't able to find an answer in the documentation
C# tries to resolve the method group by looking at the number of arguments you passed, as well as their types.
public void Test()
{
Foo(3, null);
}
void Foo(int x)
{
}
void Foo(int x, int y)
{
}
void Foo(int x, GameObject y)
{
}
void Foo(int x, Transform y)
{
}
This is a compile error because it can't decide if you wanted the third or fourth method
Getting rid of the last method makes it work, and it winds up calling the GameObject-taking method
That makes a lot of sense. Thank you for explaining. What is best practice for sanitizing this? I'm assuming it's simply to make sure to check for null, before deciding whether or not to run the normal version or the override.
I'd think that the drag-and-drop code should always call the method that takes a slot index
unless you can drop an item somewhere to just put it in the first available slot
in that case, you'd still have two different code paths
one for dropping an item on a slot, and one for when you don't
My plan is, if you drag an item into the inventory window, but not onto a specific slot, it runs the generic AddItem version instead.
How do I fix this problem?
My code reads the normal of the surface below it to determine the move direction. This works fine on flat surfaces or very shallow slopes, but if the player is at a certain point on the slope, it reads the normal of the ground and uses that to determine move direction, instead of the desired result, which is reading the normal of the slope as soon as it touches it. This problem has plagued me for weeks and it haunts me to this day
Here's a diagram of the issue
I had to use spherecast to fix this in my game.
Warning, however, spherecast is... weird.
I don't remember the details, but Spherecast has a bunch of weird bugs associated with it.
It's ok I just want it fixed 💀
I just remember it took me longer to work around the spherecast bugs than it did to make the entire movement system.
Actually, I might have straight up switched it for a dedicated hitbox.
Let me check and I'll get back to you, aight?
Absolutely, tysm
I mean, I opened Unity Explorer and looked into a game I like, and it used a dedicated hitbox as well, so...
The gist of it is, you'll never fix the weird jank with using raycasts to detect the ground, there will always be SOME kindnd of weirdness going on, so you have to use something eelse.
OH
I remember what it was.
Warning, if you do use Spherecast, if Spherecast spawns inside of something, it ignores it.
so if you spawn the spherecast imagine there's a sphere that has to spawn, and if that spawn point's radius intersects anything, it ignores it during the cast.
I got around it like this:
private void GroundCalcs()
{
belowMe = new Vector3(transform.position.x, transform.position.y - groundDetectRange, transform.position.z);
aboveMe = new Vector3(transform.position.x, transform.position.y + 1f, transform.position.z);
groundBelow = Physics.SphereCast(aboveMe, controller.radius, Vector3.down, out hit, groundDetectRange);
//check if the player is on the ground.
if (!groundBelow)
{
//if there isn't ground under the player, check if they were touching the ground last frame. If they just now left the ground, set the gravity to zero, otherwise, increase their falling speed.
if (!ground)
{
fallingSpeed = Mathf.MoveTowards(fallingSpeed, terminalVelocity, fallingAccel * Time.deltaTime);
}
else
{
fallingSpeed = 0f;
}
ground = false;
}
else
{
fallingSpeed = gravity;
ground = true;
}
//add falling to the player's movement.
direction.y -= fallingSpeed;
}
Notice how I call the Spherecast ABOVE the player's root, THEN aim it down. this is to make sure when they're standing on the ground, the spherecast can never spawn intersecting it.
that is just how physics casts work in 3d. You simply can just start a capsule cast in the exact position of your player then cast it downwards and not have this issue. Unless your player is in a wall, which would mean you have a bug unrelated to this
I was using spherecasts in the exact position and size of the bottom of the player's capsule, IIRC, and it was behaving inconsistently. I don't recall what all I tested, but it was very finicky and took a lot of mothering, even with exact values.
The problem with SphereCast is that it will ignore any colliders it starts inside of.
You can use OverlapSphere to check for any colliders that you're already overlapping
Although that's not going to give you a normal vector.
Yeah, and in my experience, that makes it finicky, even if you're using precise values. I know I'm biased, but you can't fathom how long it took me to finally get it working 100% consistently.
But you could ask for the closest point on that collider and then use the vector from that to yourself as the normal vector, I suppose
My solution has to simply been to never have any slopes
I...should update my humanoid locomotion system
Gigabrain
I only recently added gravity. entities were bumping into each other and slowly floating into the air
eventually they detached from the navmesh and got confused
But that... doesn't fix my problem. The problem isn't that it doesn't think I'm grounded, the problem is that it thinks I'm standing on the flat ground instead of the slope.
Also, I'd like to just use the normal built in gravity.
IIRC, Spherecast can return the normal of the first surface it hit, let me look up the documentation
Found it
Yeah, you should be able to use Spherecast to return the normal of what it hit.
Which would let you handle that nicely, I think!
Yes. All of the various casts produce a RaycastHit.
when talking about player movement and slopes, "built in gravity" doesnt work. you wouldnt want your player sliding down every slope. Think about the case of running up and off the edge of a slope, players should just fall down immediately. Built in gravity will make it continue in its path while slowly falling down, like if you rolled a ball off a slope.
You can just turn gravity off if they're on a slope. Also, I'm planning on the player keeping their momentum after they go off a slope. Unity gravity will work fine for me
keeping vertical momentum sounds weird if these are supposed to be humanoid characters. Im not a major fan of toggling gravity on/off. Just keep it off and store what it currently should be
example: lets say that u are running up a slope. velocity is (whatever, 5, whatever), x and z dont matter here.
When you run off the slope, aka you are not grounded and nothing is below you, you are going to keep going up because velocity.y will take time to go from 5 to 0 to negative. Its fine to keep horizontal momentum here, that can be reasonable.
Cool, I can just check if you move off the slope and then cap your y velocity. Doesn't seem like a gravity issue
Ok so you arent using built in gravity then if you are modifying it yourself
It's... literally just modifying player velocity
ive experimented around a lot and i found keeping track of gravity yourself is the most desireable. but 🤷♂️ do what you want i guess
no need to find work arounds and edge cases when you control what it is entirely.
how do I remove a sprite from a sprite sheet?
Not really a code question, but I'm pretty sure you can just click the sprite (in the spritesheet, not the asset), and hit delete on your keyboard
i tried that
But ask in #🖼️┃2d-tools if that isn't it
o ok thx
There's a way to make the bool value in one script correspond to the bool value of another script using reference values, right? Because I have this function and it's not working
{
hitBuffer = inHitBuffer;
}```
Tried doing the inverse and it's still not cooperating
You aren't setting the ref variable
You are using it
Which means inHitBuffer is untouched
How would I go about assigning it correctly then?
inHitBuffer = something
Yeah, I tried that. It's still not working
What are you expecting to happen?
And this seems weird
Why do this at all?
I'm trying to make it so that the value of two bools in two different scripts are always exactly the same
But WHY? That points to an architectural issue. You should not need or want to do that
You can't really do that in C# in legal ways.
If you MUST, then have an event in the setter of a property
But I can't see a reason that you must
You could have a reference type wrapper for your bool and change the bool in it, but I feel like you're trying to do something unreasonable.
Hey! I'm looking for some help with an error I'm getting when I followed the Samyam tutorial on making an online leaderboard. I followed all the steps thuroughly and it keeps giving me this error: Could anyone help with this? If they need any more information, please let me know!
The error is pretty self explanatory. Did you check the line that throws it and confirm what string you're using there?
I believe so. VS wasn't telling me anything was wrong.
It wouldn't tell that something is wrong, because it's a runtime error, not a compile error
You need to debug the value that you handle there at runtime.
oh ok. I should revise the code in the video. If i'm getting the same error, I'll check back and try that
Would there be something wrong with the parsing?
If it's an error with the string, the parse converts the int to string so I feel like that could be where it's coming from
There could be, depending on the text value. This kind of input is usually supposed to be handled with a try catch or validated before parsing.
It's the other way around. you convert the string to an int there.
Oh. didn't catch that
That's what the error is saying too.
true. the video did cut to when she was using the parse so i don't think it's entirely required
I was wrong
What's not required?
parsing. I'm very new to this kind of thing
You are doing it though
So obviously it's required by the tutorial
Int.Parse is parsing a string I to an int.
It's giving me a stack overflow when I do this
Agreed. there's not much going on in this script so in my eyes, there's not too much to work with in terms of finding the error
You really have to provide more info when you say these things. Show what you did
I really don't understand what you're saying. There's clearly an error. And it's clearly caused by Int.Parse
You should either add validation or make sure only valid string goes into it.
public delegate void SetBool(bool b);
SetBool setBool;
bool hitBuffer { get { return hitBuffer; } set { hitBuffer = value; setBool(hitBuffer); } }
public void AssignHitBuffer(SetBool inSetBool)
{
setBool += inSetBool;
}
ok. I will try that. thank you
If you're asking in this channel, you should be able to debug that error.
If you don't know how to debug, I suggest moving to #💻┃code-beginner
thank you
What is going on with that method? What is the logic behind it. Looks like it would cause recursive calls maybe?(which would explain the stack overflow) It's kinda confusing me.
You still haven't explained why you would ever want to be syncing these two bools. Seems like a really bad way to do things to me, and it should be abandoned for better architecture
Oh I see what you mean now
You assign hitBuffer but your property is called hitBuffer, therefore causing a stack overflow . . .
Use proper naming convention for the property to avoid that issue . . .
i dont get any error but my i dont see the package in project tab
A coding channel is not any better. Please use the right channel, or just post it in #💻┃unity-talk
npm ERR! code ENDENT
Terminal (Ctrl+)
npm ERR! syscall open
DIE JG CONSOLE
npm ERR! path C:\Users\maqui\Downloads\JooBot-main\package.json
npm ERRI errno -4058
npm ERR! encent Could not read package.json: Error: ENDENT: no such file or directory, open 'C:\Users\maqul\Downloads\Joobot-main\package.json" npm ERR! encent This is related to nom not being able to find a file.
npm ERR! encent
npm ERR! A complete log of this run can be found in: C:\Users\maqui\AppData\Local\npm-cache\logs\2024-03-14T09_06_07_3032-debug-0.log PS C:\Users\maqui\Downloads\Joobot-main> npm
It says the package.json is nowhere to be seen
But its there
I see it myself
Please use the right channel #🔎┃find-a-channel
This channel is for general coding questions regarding Unity
Guys I have a question, I'm using a script to define the behaviour of my object (let's say object A) then I assign it to a gameobject in the editor, but now I would like to create a a new script that let's me create object A. Object A implements monobehaviour class, and has a start and update function, and I assign public variable some values to it in the editor. My question is now if I want to create a script that initiates object A, how should I proceed ?
I read that I would need to change it to a scriptable object and then could use a constructor, is that the best way to do it?
Ah, sounds like composition approach so yeah SO is a good idea.
public class BaseObject : Monobehaviour
{
//fields
public Assign(BaseObject_ScriptableObject SO)
{
//assign fields
}
//could also do a copy constructor, or instantiate and do the assignment all in one here
}
public class SpawnObject : Monobehaviour //could make this a singleton
{
BaseObject baseObjectPrefab;
public BaseObject InstantiateObject(BaseObject_ScriptableObject SO)
{
BaseObject newBaseobject = Instantiate(baseobjectPrefab);
newBaseobject.Assign(SO);
return newBaseobject;
}
}```
Something like that?
you can't use the constructor of scriptable objects directly either fwiw, either way you have to let Unity instantiate it, so making a prefab is probably the way to go
for good practice, would you guys recommend managing stuff like players stats (health, maxhealth, speed etc..) on the player itself, or make a managing singleton?
i'd keep it on the player if the project is large enough, but you can always have references to the player via singleton
PartyManager.Instance.members[0] = first player of the party, ect
Oh, to clarify, i will have a single player.
Reason im asking is stuff like healthbars also need to know about player HP, so is a reference to healthmanager or playermanager better practice for example
Depends how you're accessing it on the scene, but if you're doing colliders, you can just grab the stats directly from the mono
Its colliders yeah
i guess ill just put a singleton playermanager mono on my player?
Doesn't need to be part of the player's object, it can sit out anywhere in the scene as long as you bind the reference to the player's gameobject on it.
Right, script will be the same for both ways tho so ill fuck around a bit and see
thanks
ye, either way works really, I don't usually keep stats on the singleton personally, but I do keep references to the gameobject + stuff like input and camera
upgrades and stuff I could see being cached on a singleton manager
Yeah, all difficult stuff. My project is getting big big and it feels like at this point everything needs to know about everything. :/
yep
wondering what the most up to date multiplayer networking system is, should i be using photon or NGO or something else?
is there any issue with entities package with IL2CPP and unsafe code? bcs when i try use IL2CPP and unsafe code, unity reload and stop at updating scene for 1h and nothing happens
Guys idk anyting abt unity and i wanna do programming Where do i start
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Is there an easy way to figure out where one of these guys is coming from? cant double click
that's an editor error, not likely related to your code at all. pretty common when the animator is open, but could be caused by any window that uses the graph view like shader graph
Does anybody know if the crash logs stack trace has the deepest call on top or on bottom? On windows
As in, actual crash stack traces, not exceptions
How can I modify this ray code to ignore a layer, so that it does not block the raycast?
while (Input.GetMouseButton(0)) {
var ray = mainCamera.ScreenPointToRay(Input.mousePosition);
m_SpringJoint.transform.position = ray.GetPoint(distance);
yield return null;
}```
I'm used to doing it with Physics.Raycast but that's pretty much it
All ray.GetPoint does is ray.origin + ray.direction * distance. It doesn't have anything to do with layers or raycasts at all
use a layermask. But this code doesn't even do a raycast at all
I have a class (call it BaseClass<T>) with a generic type parameter. The parameter is used to give the class a field that holds its configuration data. So, FooClass<FooData> can have a FooData and BarClass<BarData> can have a BarData. In FooClass<FooData>, I can access data.someFooField.
BaseClass<T> is also responsible for setting up the configuration data.
This generic type parameter is "invisible" outside of the class. You cannot get a FooData out of a FooClass, and the type shows up on none of its public methods.
I want to be able to reference any BaseClass<T>, but since it's generic, that's impossible.
So far, my solution has been this mildly ugly hack: BaseClassImpl<T> derives BaseClass and defines the config data field. FooClass<FooData> and BarClass<BarData> thus derive from BaseClassImpl<T>.
I'm basically "covering up" the generic type with an intermediate class.
This works, but it's now causing problems.
I want to define a new class, SpecificClass, that has some extra functionality. However...
- If I derive from
BaseClass, I'm going to have to define aSpecificClassImpl<T>again, including the logic used to set up the config data. - If I derive from
BaseClassImpl<T>, I'm back where I started:SpecificClasshas a generic type parameter on it!
The alternative is to not have a generic type at all, and to just make FooClass and BarClass declare a field to hold their config data. They also have to set their config data up (fortunately, I can extract that into a static generic method that looks up the default data for them).
I'm not a huge fan of that because it requires duplicate code in every single class.
Any thoughts on this? I asked about this a few months ago, and I wound up going with this "covering up" strategy.
it's hard to judge without seeing any actual code but does the base class have to be generic? if it's only used privately then surely the different data objects have some common interface or base class you can refer to it by
the key point is that FooClass and BarClass need a field that holds a FooData and a BarData, respectively
why?
if you can go with the field idea I'd go with that honestly
public class HearingConfig : Config
{
public FloatConfigItem noiseFloor;
}
public class HearingConfigData : ConfigDataImpl<HearingConfig>
{
public float NoiseFloor => GetFloat(config.noiseFloor);
}
the Hearing class has a HearingConfigData field, so it can access data.NoiseFloor.
GetFloat looks up a float value from a Dictionary<FloatConfigItem, float> to decide the current value (that's part of ConfigData)
The same "generic hiding" thing is going on here, since I want to be able to handle arbitrary ConfigData instances elsewhere
it's a conflict between:
- I want specific classes to have easy access to their specific configuration data
- I want to be able to make a big list of
ConfigDataso that I can serialize everything
HearingConfig is a scriptable object asset that everyone shares
HearingConfigData is a plain-old C# class that each instance of my Hearing class has (and which is populated with saved data)
FloatConfigItem stores things like the name and description of the configuration item, plus the default value, the increment for sliders, ...
what does ConfigDataImpl do with config?
public class ConfigDataImpl<T> : ConfigData where T : Config
{
protected T config;
public void Setup(T config)
{
this.config = config;
foreach (var item in config.items)
{
Init(item);
}
}
public override Config Config => config;
}
It needs the Config object so that it can iterate over every ConfigItem and set itself up with default values.
Then it holds onto the T so that I can access members from it here
The alternative would be to directly give the Hearing class that FloatConfigItem, and to have it directly call GetFloat on its ConfigData.
Then there'd be no need for generics at all here.
I'd just do float noiseFloor = myData.GetFloat(noiseFloorConfigItem);
i think if you can avoid it, that would make things a lot simpler
This would require assigning a FloatConfigItem asset to each individual instance of Hearing, and that's completely redundant.
i was thinking if you get rid of the config field in the base class it'd make things simpler too, you could still have Config as an abstract property if you need it
that's true (and I've done something similar in several places)
but all the generic param is doing really is changing the type of field it's stored in, so making each subclass declare the field itself is basically the same thing
I could give HearingConfigData a HearingConfig config field and then override that abstract property.
And that's basically identical to the original problem I was describing here. #archived-code-general message
yeah, exactly
It's the same problem in two different places.
I don't like the code duplication, but the generic class is creating a lot of ugly code too
plus the cognitive load of having Foo and FooImpl and generic type parameters flying everywhere
private HearingConfigData data;
public override void Init()
{
ConfigDataMaker.Get<HearingConfigData, HearingConfig>(out data);
}
god i wish it could infer that generic type parameter for me
this replaces this lovely code
public abstract class ConfigurableModule<TConfigData,TConfig> : Module where TConfigData : ConfigDataImpl<TConfig>, new() where TConfig : Config
{
protected TConfigData data;
[SerializeField] SerializedConfigData defaultConfig;
public override void Init()
{
data = new();
data.Setup(OwnConfig);
data.Read(defaultConfig);
}
oh no
maybe what you really want is dynamic 

Thanks for the help! I need to go stare at this some more, but I'm a lot less married to this funny "covered up generics" idea now
it's basically down to where you want to draw the line in your hierarchy where you declare the concrete type, and everything above that needs to be various levels of generics
ive set my own personal constraints to only ever using a single generic parameter (utility scripts are a different story though)
in both cases, I don't actually need to get data back out of the generic-typed class, other than that one protected field
So it'd make more sense to have each derived class declare its own field and provide access to it through a property
no more generic parent type
What about an IBaseClass? Since none of your public API surface cares about the generic which is an implementation detail.
I originally needed the generic type here because Setup needs TConfig, not just any old Config object
But Setup only needs that because it's writing it to a TConfig field.
So when that field goes away, Setup can accept any Config
and now ConfigurableModule only needs the generic type parameters for its own data field
and when that goes away, nobody needs generics anymore at all

a few extra lines of code per module class is worth not having...this mess
Is there a reason this collision might not register even when both colliders are most definitely active and the collision between the two layers they're on is also supposed to be active?
What does "not register" mean? What are you expecting to happen exactly?
Do they have rbs?
They both have rigidbodies, yes
Well, the weapon doesn't have a rigidbody. I mean both capsules do have one
Is one of them a trigger?
Hey guys quick question. Please @ me when you answer. When you have a physics2d.raycast if you filter by layer and will it bypass through other lays searching for that layer or does it stop at the first thing it hits then return false if not of the proper layer.
it completely ignores anything that's not in the layermask
as if it's not there at all
it will only hit things in the layer mask
Ok thank you
also, anything outside the layer mask doesn’t affect performance
if you raycast into 1000 colliders, that might take 1000 units of time. But if you filter by a layer mask that only includes 10 of them, it would take 10 units of time.
roughly speaking
Are you sure that's true? I don't know how they do the layer filtering in the native code but it's entirely possible they have to filter through them.
i did testing with Physics2D. All the queries I checked behaved like that
idk if that also applies to 3D
They are different engines
it's not necessarily the same
Box2D vs PhysX
I wouldn't be surprised if it's true, just not a guarantee
in this case it was raycast2D
oh true
i can make no guarantees about 3D
the 3D engine does a lot of things differently. Just with a slightly similar sort of API
because it’s all unity (which deals with components).
For some reason my ray isn't detecting ground properly. I'm afk right now. When I get back I'll send code and sc.
Hello
I added a menu scene, with 3 buttons (play, options and exit)
I made the script for the buttons, but they don't work
I even specify wich scene should load when I press play
@delicate flax @leaden ice Thank you so much i managed to make it work!!!
first verify the buttons are clicked in the first place
they are
show current code then
@leaden ice here is everything
if there is anything I am missing let me know
like anything you needs SC of
embeds aren't working rn
the images aren't working yeah 😦
oh dang...
maybe find a hosting site and link them?
Can I DM them?
yes
Things look ok at first glance but it's hard to say exactly where the raycast is
turn gizmos on!
gizmos??
Yes. One of them is indeed a trigger
Im semi new to unity whats gizmos?
Top right button Game Window
Then you can see your Debug.DrawRay
Your DrawRay isn't correct though
Debug.DrawRay(new Vector2(transform.position.x, transform.position.y - (playerCollider.size.y * transform.localScale.y / 3)), -transform.up, Color.red, 0.05f);```
It should be this:
```cs
Debug.DrawRay(new Vector2(transform.position.x, transform.position.y - (playerCollider.size.y * transform.localScale.y / 3)), -transform.up * 0.05, Color.red);```
oh color is after?
the last param is time
it displays for that long
the distance and direction are combined in the second param
I turned gizmos on. the. the ray is spot on.. now I am more confused..
pic is in same link
try again after the change I suggested to the DrawRay
I don't think the ray is long enough
I'm making a gun right now, coding the recoil system. I want the rotation of the gun to kind of "overshoot" when lerping to the desired rotation.
Like, it goes over the target rotation, if it started from 0 to 90, it goes a bit over that. I've tried and got... something. It's just a mess and I'd be embarrassed to show it, but if I must, I'd gladly do it then.
without code what exactly can we help with lol
sorry my bad
For collision detections, do I need to have both Rigidbody 2D and Collider 2D on the gameobject?
depends what kind of collision detection you're talking about and which object you want to put your script on
The rigidbody needs to be on at least one of them usually
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Basically I have a Bullet prefab that I'm sending towards an Enemy prefab. Bullet has Rigidbody 2D and Collider 2D while Enemy only has Collider 2D for now, no "Is Trigger" is checked, in the Bullet's script I am using OnCollisionEnter2D to detect collisions, but it's not being called
It's entirely possible the bullet is too fast and is just passing through the target in between physics updates
Is the rigidbody on the bullet's collision detection property something other than "discrete"?
btw this would only yield -1 and 0
curve.Evaluate(time) * Random.Range(-1, 1),
integers are max exclusive
oh yeah right thats true
No, it's discrete
Idk what's considered too fast honestly, but I don't think that is the case, it's only 10 * normalized direction vector
Try changing it to continuous and see if that changes anything
On both objects?
No, just the bullet
Nope, that didn't fix it
how you are moving the bullet also matters
Translation for example will not give you accurate result
Upon instantiation, I assign a constant velocity to the bullet's Rigidbody component
why doesn't the enemy have a Rigidbody? It doesn't move?
Anyway is the bullet visibly colliding with the enemy?
If it is, it's not a tunneling problem
I have not implemented that yet so I didn't add the component
Just try adding it, you can make it kinematic
i think even if u use the correct rigidbody moving method and have it set to continous then very fast moving small objects can still pass through walls and stuff for some reason... idk why and idk how to fix that
never had issues with Continuous tbh
unless we're talking speeds over 1000 units
I am making scenes at Runtime. When I do SceneManager.CreateScene - it only does it additive. Anyone know why? Anyone know how to fix that? I still only want the new scene active.
Yeah? It is moving towards the enemy, disappearing, and then reappearing on the other side
I did not understand the tunneling thing, but I checked both z coordinates and it's 0
that doesn't sound like it's colliding
sounds like it's going right through
can you show screenshots of your setup?
Oh you mean colliding as in hitting and changing direction, velocity, etc.?
yes
Yeah that's not happening
then it's not colliding at all
show screenshots of your setup
Especially showing the components on each object
Bullet (I tried both Discrete and Continuous for collision detection):
Enemy:
If, for whatever reason, the shape of the bullet may influence this, this is what it looks like:
public class mainMenu : MonoBehaviour
{
public void playGame ()
{
SceneManager.LoadSceneAsync("Level 1");
}
public void quit()
{
Debug.Log("Quit!!!");
Application.Quit();
}
}
I tried with index, with (1) as the next index and nothing
and you verified the buttons were working how ?
how isn't a yes/no question
what?
I asked how did you verify the buttons themselves were working
You said the buttons work but the script don't work
Tbf the original question is very weirdly formatted
With the "how" as the last word
yeah kind strange I was following up from them saying this
I have different colors on them
ok so the buttons hovers are indeed working?
yes
did you try the actual LoadScene method
Too easy to read fast and interpret the follow-up question as
and you verified the buttons were working ?
Human brains are not perfect, you sometimes miss stuff
dw
LoadSceneAsync is async so its running in the background, maybe its loading and you're not noticing and you keep pressing ?
Nah they're very far from basic lol, I've seen wayyy worse here
gotta practice more 😅 been in US 10 year
Also, The Obvious™️, have you added your scene to the Build Settings list?
yes
Try specifying the index instead of a string if you haven't done so yet. Strings are much more error-prone, like you can add a space at the end by mistake and not notice it, but I guess you'd get an error about the nonexistent scene at this point
nevermind
fixed?
I put the script in the Onclick function and it didn't saved
yeah

I just hate when I put things and they don't save even if I press the save buton
the scene should save, but its not saved if you have *
@leaden ice @rigid island It seems like Kinematic and Kinematic collision doesn't work for some reason, when I changed it to a trigger and modified the method it worked. Just thought I'd let you know 👍🏼
your bullet is kinematic
it's not going to collide with stuff
how are you setting velocity on kinematic 🤔
it works in 2D actually
Ahh 2D
OnCollisionEnter(2D) is for dynamic rigidbody collisions only
Ah, I just set it to kinematic so I don't have gravity
Should I set to dynamic and set gravity scale to zero?
yeah that's not what kinematic is for
kinematic turns it into an unstoppable object that's not affected by anything else
what are the pros and cons of utilizing a multi scene workflow with ui, gameplay, etc on seperate scenes vs just having everything in one scene?
im failing to see the purpose of complicating everything by having to use a service locator or something like that to easily talk between scenes

elaborate please
some projects it makes more sense to have multiple scenes, especially when the map is big and you need to work with multiple people
multi-scene setup allows everyone to work on their section of the map without creating Merge conflicts on Version Control for example
im not talking about having seperate scenes for each map
Loading entire map is more costly then splitting to Multiscenes loading (look at firewatch does this well)
I don't think necessarily "ui" and "gameplay" are generally the boundaries used for multi scene workflows
im talking about having each element in its own scene, like having a bootstrapper scene which holds your save system etc, then having a ui scene, then having the actual "map" scene
but I guess an advantage in general is that the more scenes you use, the less VCS conflicts you have to deal with
yes, i was just giving an example
all those systems are scenes?
when you say "UI scene" do you mean like a main menu scene?
why not just prefabs with DDOL
i know, thats why im questioning if it's worth it to setup something like this
I've tried a separate menu scene before. It's a lot of extra hassle to handle the loading and unloading.
I did not see a very obvious benefit
this is the video im questioning https://www.youtube.com/watch?v=JFP-cCFID7o
Learn how to load multiple scenes asynchronously and additively, at the same time in Unity, with plenty of customization and a load screen. Load and Unload multiple scenes at the same time with less overhead and continuous progress reports!
Want to support me? 😀
Buy me a coffee! https://ko-fi.com/adammyhre
🔔 Subscribe for more Unity Tutorials...
yeah to me just seems more work than its worth
someone please show me a script code for 2d movements
me personally? I personally try to make everything in one scene when possible, only keeping the important bits in DDOL like singletons
like the PlayerUI for me is a prefab canvas that spawns with the player so I can put player anywhere it always has UI
the current game I'm working on leans towards a single scene (individual levels)
so my menu UI just lives in DontDestroyOnLoad
Single scenes is definitely a lot easier
but other projects I have like for pre-made levels , I cannot have one scene for that multi-level single scenes make sense
but not not singletons or any logic
agreed, i don't see the purpose of complicating things like shown in the video
theres a weird gap in unity tutorials where most are terrible and way too basic then the rest are way overcomplicated
the youtuber i posted has a lot of very interesting videos but I feel like you can accomplish the same thing with way less overcomplication, but maybe im being naive
Can I somehow set or get/modify LIghtingSettings at runtime?
This was in an open-world game (well, it had like three places to go, but...)
so I had lots of additive scene loading already
depends what
mostly yes
com on man just google it..
there are hundreds of scripts
I mean, at a bare minimum how can I load A LightingSettings asset and assign it to the scene? Docs imply its only in UnityEditor
hope I find something that really works
💀
i need basics
cant you just switch out the quality prefabs or SO whatever they are?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
then you should learn basics first so you kinda understand what you're copying
yea
otherwise you're just blindly copying, if something breaks you're screwed
Maybe hop on over to #💻┃code-beginner, but honestly, there are THOUSANDS of blogs, videos, classes on Unity basics, including 2d character animation, movement, and collision.
yes #💻┃code-beginner has good resources pinned
I'm doing a lot of procedural generation, so I was attempting to build scenes 100% from code and no editor interaction or prefabs 😄
Sometimes Unity just isn't built for that 😄
hmm you mean like bake lighting you prob need realtime lights etc
I'm not doing any baked lighting
idk thats more challenging to optimize generated scenes. I dont know much about runtime gen
Does anyone know what's wrong with this code?
public void playAnimation(Animator animator, float animation, string parameter)
{
animator.SetTrigger("look");
StartCoroutine(Animating(animator));
}
private IEnumerator Animating(Animator animator)
{
while (animator.GetCurrentAnimatorStateInfo(0).IsName("look"))
{
Debug.Log("Waiting");
yield return null;
}
speaking = false;
Debug.Log(animator + " is done doing a non-speaking animation.");
currentSpeaker = null;
}
My code never goes into the while loop but it plays the animation state fine in the scene
eg the whole static batching
you don't need an asset; the asset just holds a LightingSettings object
Yes, but I can't assign a LightingSettings object to a scene.
you verified the bool is true ?
Wanna tell us what behavior you're expecting vs what you want
Exunchtly 😄
I would store the bool inside update instead then check in while loop @arctic plume
Update()
...
isLookAnimation = animator.GetCurrentAnimatorStateInfo(0).IsName("look");
...
IEnumerator Method()
...
while(isLookAnimation )
//etc
...```
this contains the Environment settings
as opposed to the settings used when baking lightmaps
I forget how you actually access the current RenderSettings, though..
Most is static I think
oh, duh
I guess it just gives you the settings for the active scene?
Note that render settings are per-scene.
RenderSettings.skybox = material; works for my skybox builder
Right, I assume its all the active scene that you're setting (which is odd AF... )
well, the Environment settings are global, so I guess you can only use one scene's settings at a time anyway
basically after the look animation, the character says something
And I use the Coroutine to wait for them to finish looking
But for some reason they start saying their line while looking
did you try what I sent?
its possible by the time the coroutine while loop hits the IsName is false
Sure, but what are you supposed to do, have a script that init's a scene with all of its render settings? Id on't even see where to update this. Unity can really make you feel dumb sometimes
What are you trying to accomplish here?
I'll try that now
also since you will store it inside a variable you can look in the inspector like [SerializeField] private
I'm doing a lot of procedural generation, so I was attempting to build scenes 100% from code and no editor interaction or prefabs
hi
does anyone knows why vector3 doesnt show up in inspector ?
`[SerializeField]`
public Vector3 pos;
You probably have a compile error somewhere
You only need public OR SerializeField not both. Your error is elsewhere
Can you have that show in inspector? I thought you need a custom editor gui for v3
Vector3? no
hm, yeah, so the RenderSettings are serialized as part of the Scene asset. Once you're in the built game, I don't even know where that asset winds up
i tried both and I also have other public variables like bools , strings ...etc
yet only vector 3 gets ignored, no errors, no warnings .. no nothing
The alternative is definitely going to be setting the render settings yourself after the scene loads
oh, wrong Vector3
you're using System.Numerics
You're probably using the wrong Vector3
get rid of that using directive and replace it with using UnityEngine;
Yeah that makes sense, but it seems absolutely absurd that its a static... why does unity make these weird mistakes? What if I have two scenes loaded?
only the active scene's render settings matter.
Even with stacked scenes? Only the active's apply?
nope , its UnityEngine.Vector3
📃 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.
Yes.
The HDRP moves a lot of stuff out of RenderSettings and into the Volume framework
but I believe the built in RP and the URP both keep a lot of stuff in RenderSettings
Yeah I'm using URP
Hi, I'm trying to setup couch coop with different playerinput components for different players and having a problem when it comes to rebinding. When I try to rebind using the RebindingUIPrefab asset the new input system comes with, only the first User gets it's action rebound. This is even weirder when you consider the fact that the first User isn't even using the correct control scheme the binding im trying to rebind has. How should I go about fixing this issue?
Image 1: Shows that the wrong user is getting rebinds. (Controls get disabled while rebinding.)
Image 2: How I set up the PlayerInputs. Each object there has their own PlayerInput Component.
Image 3: Shows how the control im trying to rebind doesn't exist on the Keyboard2 control scheme even though it is getting rebound in the PlayerInput component that's setup to be in Keyboard2 control scheme.
That didn't seem to help either :/
I don't get why it never is true, if I clearly see it happening in the scene
can you ss the animator for this object
You want a picture of the animator sheet?
yeah preferably with the look clip selected
@leaden ice Thank you for your help , as it turned out, I had a custom editor for this script and completely forgotten about it lol
Sorry if it's messy, animation isn't my strong suit haha
all good. Hmm is the bool never get checked on / is never true? you looked at it in inspector yes?
an easier way would probably be to just use an Animation event
What's an animation event?
hey everyone, im trying to make a gizmo line that follows multiple vector3 points
essentally every update, im putting the position of the bullet into a list and i want to display those points as a line
ive tried using Gizmos.DrawListLine(), but it doesnt work
it says "Each pair of points from the points span represents the start and end of each line, so Unity draws the first line from points[0] to points[1], the next from points[2] to points[3], and so on." So essentially, i have an odd number of points in my array
but i dont want it to go [0] to [1] then [2] to [3], i want it to go [0] to [1] to [2] etc.
then add each vertex twice?
then it would go from 0 to 0 then from 1 to 1
i guess i could re-add every odd index
wait, just looked on the unity docs and Gizmos.DrawLineStrip is exactly what i need
yepp lol
Are you doing this for editor or for gameplay?
just editor, i have line renderer tracers for gameplay
What are the downsides of using ObservableList vs using just List? ObservableLists almost sound too good to be true, for when you need to react to changes in a list.
you try to invoke methods whenever you alter the list.
if you don’t need to invoke anything, it is strictly inferior to a list
I made the changes but I have to take away 90 degrees from the angle or it points 90 degrees to the left of the player.
But it works still
I can't find any documentation explaining how exactly to use an ObservableList to trigger a method.
Does anyone here know where to point me in the right direction?
So far, the ONLY thing I've been able to find is not Unity's inbuilt ObservableList, but what seem to be people's custom implementations of it?
Should really just do barrel.up = direction;
Skip the whole angle calculation entirely
The docs have the events in them
itemAdded and itemRemoved events
YEah, what I'm struggling with is figuring out how to USE them, I've tried making it like I did my otheer event handler, but ssomething is differnt about the syntax or something, and I can't find any information on what I'm doing wrong.
I'm trying to add listeners for the event, but no matter what I try or look up, it just throws syntax errors.
If you click on the link for either one inside, it shows you how the delegate is defined. It uses an eventargs which isnt too common I guess to see in unity. You can easily make your own event for a list and use that.
You should be able to get your IDE to autocomplete a method for it tbh
It is fighting me every step of the way, and none of the other events I've made seem to be anything like this. I'm struggling hard.
I'm trying to figure out how delegates work now, but the syntax and formatting for the documentation on those is ALSO different and isn't helping me figure out what to do.
public delegate void ListChangedEventHandler<T>(ObservableList<InventorySlot> sender, ListChangedEventArgs<InventorySlot> e);
I have this, but I have literally no clue what it does, or how it works, and what I've been looking up to try and explain it to me is talking about stuff utterly unlike this.
It’s a uni assignment. One of the requirements is outputting the angle in degrees
I absolutely cannot get my IDE to tell me what the heck it wants.
im not sure where InventorySlot came from, that should be T in their definiton of the delegate. but this is just telling you it is using an ObservableList and ListChangedEventArgs as the parameters. The type of both is generic
I just want to make a script run some code when my ObservableList changes, I've been plugging everything I can think of into these damn things, but I can't get it to listen for the event, or even figure out how to access it on the object it's meant to be listening to.
Reading the documentation hasn't helped me figure out what needs to happen for that. Googling hasn't found anything on it
are you using VS? you 100% should be getting an autocomplete for this
I am using Microsoft Visual Studeo
I don't know what it WANTS from me to make it work though!
do you not see anything when you try to subscribe to the delegate?
which inserts
void Awake()
{
oList.ItemAdded += OList_ItemAdded;
}
private void OList_ItemAdded(ObservableList<int> sender, ListChangedEventArgs<int> e)
{
throw new System.NotImplementedException();
}
my test list was using ints so thats why its <int>
So wait, what is the difference between that and AddListener? Because I've only seen this thing done with AddListener.
that is for unity events, this is a c# event
Christ. Alright. Thank you very much for the help. I'll try that.
+= is a bit of syntatic sugar for what its really doing, but this is how you subscribe to a delegate
Hey I'm just wondering how I can avoid instances resetting themselves on level reload, the logic is proper, but for whatever reason if I start with an instance, load a new level and then return to the first level, the instance is null and wipes any data contained
private static PlayerWallet _instance;
public int amountToPutInWallet; // Used to accumulate daily earnings
public int walletAmount;
public delegate void WalletAmountChanged();
public event WalletAmountChanged OnWalletAmountChanged;
public static PlayerWallet Instance
{
get { return _instance; }
}
private void Awake()
{
Debug.Log($"[PlayerWallet] Awake called. Current instance: {_instance}, Current amount: {walletAmount}", this);
if (_instance != null && _instance != this)
{
Debug.Log("[PlayerWallet] Duplicate instance detected, destroying this one.", this);
Destroy(gameObject);
}
else
{
_instance = this;
DontDestroyOnLoad(gameObject);
Debug.Log("[PlayerWallet] Instance assigned and set to DontDestroyOnLoad.", this);
}
}```
your DDOL singleton shouldnt be destroyed like this, are you sure it is getting destroyed at all? you likely have the singleton inside the scene, loading the scene causes it to exist once again, and it gets destroyed.
Did you destroy the instance anywhere?
Here's an example of it in engine
On reload of the level it's detecting the instance as null
How should I re-write the logic of the DDOL, I've also tested it with other scenes, it transitions makes a new instance and then properly tracks
It's specifically only occuring if I bounce back to scene 1 instead of going to a scene 3
Are you destroying the instance prior to changing the scene or anywhere?
A ddol object won't be destroyed unless explicitly
I don't believe so, should I destroy the instance when it goes to change days?
If you are getting null, you've destroyed and created the instance again.
It's so weird, because I never explicitly destroy it when moving between scenes
I suggest looking at your code where you are returning to scene one instead of three.
public void NewDay()
{
//Increase the day counter
SO_Data_dayCycle.currentDay++;
currentDay = SO_Data_dayCycle.currentDay;
//Update Grass Tiles
SO_Data_dayCycle.grassTilesList = new bool[grassTiles.Length];
RandomizeGrassRegrowth();
PlayerWallet.Instance.PutValueInWallet(PlayerWallet.Instance.amountToPutInWallet, "End of Day");
//Saving cut data into the scriptable object
for (int i = 0; i < SO_Data_dayCycle.grassTilesList.Length; i++)
{
SO_Data_dayCycle.grassTilesList[i] = grassTiles[i].m_IsCut;
}
SceneManager.LoadScene("EndOfDayScene");
}```
Is instance one, I debugged it, the value doesn't change
End of day literally just loads the scene
```cs
IEnumerator ResultsAnimation()
{
//lop through vertical layout group children and set animation to middle of screen
foreach(GameObject panel in rewardPanels)
{
LeanTween.moveX(panel, verticalLayoutGroupGO.transform.position.x, 1).setEaseOutBack();
yield return new WaitForSeconds(0.5f);
}
yield return new WaitForSeconds(1);
SceneManager.LoadScene(sceneToTransitionTo);
}```
Nothing seems wrong with your Singleton Awake method. You've likely explicitly destroyed the Singleton instance elsewhere.
Should I just remove the singleton from the heriarchy and instantiate a copy of it on first load? do you think that would help?
Not sure how that would make any difference. Awake would occur and if there were or weren't any instances, the effects would resolve
well, when youre calling Awake (i.e. when the scene loads), it checks if the singleton is null. obviously it isnt null as it already exists, but it destroys the old singleton and sets the new one as the current instance
If the Scene is loaded again, Unity loads the script instance again and calls Awake again.
you may need to add DontDestroyOnLoad(gameObject);
Pretty sure that was in the else
oh
Relative to this #archived-code-general message
void Awake()
{
if (instance == null)
instance = this;
else
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}```
heres how i do singletons usually
Is there any preformance penality when firing a UnityEvent with a lot of calls on it? Assuming said calls aren't very expensive on their own, I'm talking specifically the UnityEvent part
say, there's a couple of hundred of objects, all registered to a single unityevent, that can fire like once/twice a second at most
If the instance isn't null and it isn't this (it'll never be unless you've assigned it prior to this line), destroy this object. Else assigned the instance to this and flag it to not be destroyed implicitly.
The difference in the one shown would be the != whereas yours is ==. They've accounted for ddol.
yeah
It's likely getting explicitly destroyed somewhere when going from scene 2 to 1 where going from scene 2 to 3 is fine.
it's being destroyed because it's not DDOL. He's turned off warnings in the console, so he's not seeing the warning where it says DDOL is only valid for root GOs which his wallet manager is not
im just wondering because if the instance exists, and is not this, then it destroys the gameObject
I figured it was his audio manager object but that would make sense - there were only two objects in the hierarchy under ddol. Good cache.
You need to enable warnings and have the Singleton as a root object. The warnings would have told you why it wasn't being placed in the ddol scene.
this is my work, dungen and terrain grid system
I am so stupid, I didn't realize that instances won't work if parented to an empty game object
We were using empty game objects to organize the heirarchy
lmao
Lookin awesome. Utilizing A* or Dijkstra's for the pathing?
the path is made with the internal functions of Terrain Grid System, choose the route from point A to point B and avoid obstacles
That tears it. I just found out that ObservableLists cannot be displayed in editor. I'm switching back to normal lists and just making my own events for it.
If you use Odin, you may be able to utilize something like this:
https://odininspector.com/attributes/on-collection-changed-attribute
OnCollectionChanged can be put on collections, and provides an event callback when the collection is about to be changed through the inspector, and when the collection has been changed through the inspector. Additionally, it provides a CollectionChangeInfo struct containing information about the exact changes made to the collection. This attribu...
So, a dictionary can create pairs, but what happens when one part of the pair is removed?
Dictionary<myList, GameObject>
For example, if I were to remove myList[1], what would happen to the dictionary entry which contains that?
I'm wanting to remove dictionary entries when their associated list is gone, but I'm unsure what happens to dictionary entries who have had one of their pairs removed.
Are you removing the pair and inserting a (null, GameObject) key/value pair?
How are you implementing the removing of they key without removing the value?
I'm doing myList.Remove(index), I'm wondering what happens to the dictionary when that happens.
The key in the above dictionary shown isn't an element of the list but the entire list.
Ahh, that's... Hmm.
Modifying the elements of the list shouldn't effect the key/value pair
so basically, the key isn't the contents of myList[i], but that specific index?
So if i removed an entry from the list, the new entries that occupy its former index would become the new pair to the former pair's gameobject???
As you've got it shown above ( #archived-code-general message ), I'm assuming you're mapping lists to game objects.
As long as an object is used as a key in the Dictionary<TKey,TValue>, it must not change in any way that affects its hash value. Every key in a Dictionary<TKey,TValue> must be unique according to the dictionary's equality comparer
I'm pretty sure that GetHashCode() for a list is just the default (which produces a value based on its address in memory)
modifying the list would therefore not mess up the dictionary
So if you remove one, it removes the other, functionally?
Remove one what?
If you have a Dictionary<List<int>, GameObject>, then removing an item from one of the lists that's being used as a key will do nothing.
The dictionary cares about which list is which, not about the exact contents of the lists.
list would be by indentity
what is the purpose of the list key, is there a fixed set of items in it?
Lists as keys feels really weird too me, like its not he best thing for a key, and sounds like you might jsut want a list of structs or tuples
If you didnt override the gethashcode then your dictionary is useless (you must have the same instance to retrieve the value)
If you override it and it returns value based on the element, then your dictionary wont work after you modify the key
Ofc you can store all the keys in some collections
But in this case then you will need another “key” to access specific list so you can just create a dictionary<another key,gameobject>
soo i need to access a variable from another script but the variable is also in another class within that script, and the class name is not the same as the script name, so how would i write that?
I'm a bit confused. You want to add Status_Burn to a list. And is there an error?
There is no error its just when i add it to the list it just adds a None status effect i can send a ss
Or is it that you want to access stuff from the child when you iterate the list? That won't work
What could i do instead then
Ah, that might be good
[SerializeField] public List<StatusEffect> statusEffects;
that is the list i made and ive got it serialized so i can show you a ss of the inspector aswell
You could put some method on the parent that the child OVERRIDES. Then the child would just change the behaviour, but you don't need access to anything other than the parent.
Yeah, send the ss
!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.
public class StatusEffectManager : MonoBehaviour
{
public delegate void StatusEffectEventHandler();
public event StatusEffectEventHandler StatusEffectEvent;
private void Start()
{
InvokeRepeating("InvokeStatusEffectEvent", 0f, .5f);
}
public void InvokeStatusEffectEvent()
{
StatusEffectEvent?.Invoke();
}
}
dont mind comments i used to have a different way i handled status effects but i didnt like it
it worked but it wasnt efficent and the way i liked it
so basically i just wanted to have a list of status effects under a entity that i can add to and remove from. then i would have a invokerepeating to trigger it every half a second to apply its effect
I have another system in my game just like it but it isnt a list on a script its monobehaviours put on the entity itself so its quite different
I had to hop on my computer to look at the code. But just on a quick look, I don't see where you initialize the list
I see this
[SerializeField] public List<StatusEffect> statusEffects;
But that is not an initialization
Maybe I'm missing something?
oh my fault i read it wrong lemme show u rq
public class Card_FireAffinity : MonoBehaviour
{
EntityStats playerStats;
private void Awake()
{
gameObject.GetComponent<EntityStats>().OnHitProjectileEvent += this.OnHitProjectile;
}
private void OnHitProjectile(ref AttackInfo attackInfo)
{
FireAffinity(ref attackInfo);
}
void FireAffinity(ref AttackInfo attackInfo)
{
if (Random.Range(1, 101) < 99)
attackInfo.Victim.GetComponent<EntityStats>().AddStatusEffect(new Status_Burn(attackInfo.Victim, 5, 1));
}
}
fireaffinity method
i thought u meant declaration originally
There is no initialization here either
something like statusEffects = new List<StatusEffect>()
Unity initializes it since its public
Oh what? Ok, good to know
I've never NOT done it
works with SerializeField too
Do these scripts need to be monobehaviour? Could be a lot simpler if they were like SO or something
basically any time unity serializes it
I can make them monobehaiours and put them on the object but im already doing something like that and I dont really wanna have a million different scripts under 1 object
i dont know how that would effect performance but it just felt wrong to do
They are MonoBehaviours right now
public class Card_FireAffinity : MonoBehaviour
are they NOT on objects?
Yeah
I don't think so, someone should confirm that though
you can
i should
but yeah SOs would make more sense
ig but other than that any reason its not working
What would be in the list then, since there is no instance of the class
like im willing to change the way im willing to do this but im really curious why i cant have it the way it is rn
You can use them to AddComponent
say you want a random ability placed on enemy etc.
Ah hmm. Ok, I get that
That could be cool too
but yeah at that point you mind as well SOs which basically do that, but the benefit is MB has more Unity Events methods built in