#archived-code-general
1 messages · Page 114 of 1
Is that for the gravity helper calculation?
On mobile so hard to go back to the scripts
Snake. 🐍
yep right here
This is the rigidbody positon of the projectile
Ah nice
Realistically the gravity source should probably be a static rigidbody and be passing in their own rigidbody position instead of transform but eeeeeh later.
Shits aren't moving anyway.
For now.
if they move there will be variation for sure
Ok so just to summarize. Rigidbody2D.Interpolate = Interpolate was modifying transform.position in an attempt to smooth out the movement of the object. This was messing with the gravity calculation in a frame dependent way since we were passing in transform.position instead of rigidbody2D.position.
Makes sense.
Thanks for finding this btw. Life saver.
why cant I add this prefab to the networkmanager network prefab list?
It doesnt show up and also doenst let me drag it in
What does NetworkManager prefabs type are waiting for ?
If it's not compatible (Exemple : a Gameobject) it cannot work, sadly.
Also, is your prefab in the scene or in your folder ?
What kind of networking do you use?
Unity NGO
but I think I figured it out
its a canvas wich behaves different then a gameobject right?
Canvas is a GameObject, so it shouldn't be a problem.
My NetworkObject components look different in my NGO. Are you sure you've added the right component? Perhaps there is a NetworkObject in another assembly you use.
only have one option tho
What version of NGO do you use?
I'm puzzled. The official documentation contains doesn't include versions above 1.2, while I can see only 1.1 in my package manager, but there are already patch notes for version 1.4. Perhaps I should update Unity. 😐
I installed it yesterday so yeah its prob just a newer version
the answer was this
You dont add prefabs directly to the networkmanager anymore
it has a list where you have to add it
Looks like they changed it in 1.3.1.
How much scripts would you write to make a game character that have an inventory, some generic rpg stats and the abilities to move and attack ?
Would you go :
- Inventory.cs
- GenericStats.cs
- Move.cs
- Attack.cs
- GenericRPGCharacterController.cs
Or is it better to :
- GenericRPGCharacterController.cs
Thanks for your time
it's entirely up to you. however SOLID design principles state that you should keep your classes to a single responsibility each, so the top would be preferable to the bottom
Thanks for your reply @somber nacelle
Given that I choose first answers (many scripts + 1 controller) ;
How should i handle Gameplay events ?
- Implement UnityEvent in each scripts except Controller
OR - Implement UnityEvent in each scripts even Controller
OR - Implement MessageSystem in each scripts except controller
OR - Implement MessageSystem in each scripts even Controller
Thanks for your time
I'm trying to make a pathfinding grid system. units will have different grids that copy main one and change it. each grid has a field nodeArray of Node type paired to the grid class. For example NodeGrid class has a field Node[] nodeArray, and EnemyGrid : NodeGrid has EnemyNode[] : Node. NodeGrid should have a protected pathfinding method. it will work differently for each grid based on type of nodeArray. So maybe you could do something like Vector3[] FindPath<T>(T[] nodeArray, ...) where T : Node; but i dont like that. FindPath should just use nodeArray field cause they're in the same class. but obviously i cant make nodeArray protected and then in child grids change its type to child nodes.
If the game is a tiny project, then the bottom one should be enough. If it's a normal project, then the upper one will be better in the long run. If it's a huge project, then I would also split the controller so every system has its own separate controller. Model–view–controller pattern is a lifesaver in huge projects, especially when you try to add AI, networking, customization, and other things that greatly increase the game's complexity.
@hard estuary Thanks for your reply
I've seen articles online which mentions that MVC is not really adapted to unity dev
I can do scripts on unity but i am freaking lost when it comes to architecture between systems
I bought books, online courses and follow tutorials but i've never found a solid recipe that i can follow and adapt to make systems in unity
I've absolutely just learned that over time.
The system is more modular when the flow in code is one-directional. E.g. if a controller listens to the model, but the model doesn't listen to anything, then you can easily replace the controller with another one (e.g. AI controller or network controller) without having to do any changes in the model itself.
yeah, this is something I've discovered: it's a lot better when you have a nice neat tree, not a giant rat's nest of dependencies
if Foo has to talk to Bar and Bar has to talk to Foo, they're tightly coupled together
I just made a small win on that front last night: I used to have a component that would detect when the player got hit by an enemy's grab attack, and call a method on the enemy that handles the grab logic
Now it's just an event: OnGrab
i should really just rename it to OnHit
The sensor now doesn't care what it's being used for; it just notices when it hits the player
It surely depends on particular cases. In some cases it's handy to split it even more, in some cases it can be all tossed into a single script, while in some other cases a different kind of structure is needed.
Alright then maybe i should :
- Model : GenericCharacterData {skin,health,strength,defense,inventory,...}
- Controller : GenericCharacterController {MoveTo(),Attack(),SwitchCurrentItem()}
- View : GenerichCharacterUI{Refresh()}
What name gave you to the script with this part of code ?
it's still called "Grabber" or something; gotta rename it
@heady iris So your characters are composed with abilities
Your architecture is looking like :
- CharacterController
- Ability1
- Ability2
- ...
not in this game, but in another one -- and RTS -- they are! I made basically everything into an ability
it's a pretty nice model
I agree but i can't explain why, it's all messed up when i come to the controller !
If i take the @hard estuary example of the MVC, this is not appropriate.
Does "Ability1" should have is own data ? or does "Ability1" should read datas in "GenericController" ?
In my brain i see
-
GenericController
- Data
- AbilitiesActionsCalls
- Events
-
Ability A
- Data
- Actions
- Events
-
Ability B
- ...
I pray gods that @hard estuary will send his message and will appear to me as a revelation 🤣
As mentioned, it depends on the scenario. Controllers usually are supposed to interpret inputs (from the player's input devices or from AI or from the network), so it's worth separating it from the logic and data.
I often put logic and data together, unless there is a need of separating them. For example, you can't serialize MonoBehaviours to send them over the network, so some sort of serializable data container is needed. Another example: using ScriptableObjects makes it easier to manage units and abilities in assets, but you will need some sort of system that interprets those.
Views are necessary for multiplayer games because the host doesn't need to visualize everything. Only clients need visualization and they need to visualize only a small part of the game. In single-player games, it also can be handy in some cases.
I'm a slow typer. 😅
@hard estuary When you mention "Views" are you exclusively talking about UI ?
In my opinion, Ability should contain logic, the controller should be able to run this logic and the logic should depend on ability data and parameters sent by the controller.
UI, models, animations, vfx, all of it. Even sfx if needed. It could be split tho.
So abilities are controllers ?
@hard estuary @heady iris What do you think about this
By a controller I understand input handling and/or decision making. E.g. in the player controller it can be like: if (playerPressedAbility1Button ()) ability1.Use();, while in AI controller it will be more like if (aDepthAnalysisOfTheWholeGameStateTellsAbility1ShouldBeUsed()) ability1.Use();. So pretty much the only difference between the player character and the AI character will be the controller.
To the left :
Abilities, each is a Monobehaviour attached to the gameobject
At center :
Controller, only one per gameobject
To the right :
Controller's properties and methods
Ok i totally agree
So this kind of architecture is not completely junk
Hello! I'm trying to design an architecture for Context Steering, and can't decide what would be the best approach for multiple behaviors that would also be easy to work with in Inspector.
There'll definitely be a ContextSteeringController component, that will have a list of enabled behaviors. But how to do the actual behaviors?
-
- Each behavior is a MonoBehavior, that has it's setting serialized in fields on the GameObject. This allows for flexibility when you need to reference one of the behaviors and change somethng at runtime, but is tedious to work with in Inspector - and can result in a lot of MBs on one object.
-
- Each behavior is child of abstract BaseCSBehavior class, that's not a MonoBehavior, but is instantiated by the Controller. This isn't good since you have to somehow specify the behavior parameters, so even if it allows you to use a simple Enum array in Controller to specify what behaviors you want, you then end up with difficulties when setting up and serializing their values.
-
- Each behavior is a ScriptableObject, that has the parameters and also a function to calculate the steering forces. I like this the most, since it allows for easier sharing of settings between enemies, but I'm not sure how to solve the issue with per-object values, such as current target - especially since some behaviors have more than one target.
-
A mix of 2 and 3 - use the SO to define the parameters and select a class to use, but have a normal instance of a Behavior class handle the actual runtime. I like this one the most.
Another issue is, how to separate concerns properly? For example - if an AI system needs to double the Flee behavior range parameter, what would be the best way how to do it through Controller without directly touching that one behavior, to reduce dependencies?
Especially when there may be multiple flee behaviors, but you have a specific one you want to touch. I guess access by keyword would be the best, simmiliar to GetFloat or SetFloat for shaders/Animators.
Oh, I just found out you can instantiate ScriptableObjects, that sounds like the best solution then I guess - solves the per-instance data issue while also allowing to specify good defaults and easily assign more behaviors in the inspector.
i have graphs of class Node and EnemyNode which i use for pathfinding. I want EnemyNode to inherit from Node and have some generic FindPath method and not 2 separate ones but i dont understand how. for example field neighbor will need to be of class type so how can it be inherited?
you are not helping
i cant understand what you need....
if your algorithm depend on which grid is passed
then you need to write two different algorithms... same as 2 separate method
if your algorithm dont depend on it
then why you need generic type?
if i can make a generic find path method that will take some Node inherited class, that class's methods will make the logic different
maybe Node has virtual CalculateCost method, and FindPath will use that differently on its children
you can just FindPath(Node[] nodes)
when pass your EnemyNode:Node, it will call the overrided method
first, you need to inherit for that which is the problem. second, will it? You can store child's link in parent but it will still call parent's methods
child's link in parent but it will still call parent's methods
No, as long as it's correctly overriden (withoverridekeyword) it will select the real type's methods
Otherwise class inheritance would be pointless and C# would not have it
if you dont believe me, test it...
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
yes i tested it you're right
then i guess i can put EnemyNodes in neighbor list and it's not a problem
{
int rotation = 90 * newPlayerId;
Debug.Log("rotations is " + rotation);
GameObject go = Instantiate(playerBoardPrefab);
go.GetComponent<NetworkObject>().Spawn();
go.GetComponentInChildren<RectTransform>().rotation = Quaternion.Euler(0,0,90);
Debug.Log(go.GetComponentInChildren<RectTransform>()==null);
}``` what am I doing wrong? The prefab instantiates but the rotation isnt happening
Which rotation isn’t working ?
The quaternion.Euler one?
sure, they have a rotation
rect transforms are just Transforms with extra data attached, afaik
there's only one rotation
Yup, RT inherits it, so a less known trick is to do (RectTransform)transform to avoid a GetComponent call!
I often write (transform as RectTransform)
I have a structure preview object that follows the mouse around. When it intersects with a solid object, I want to to change color. I got all this working just fine but it pushes the player around which I dont want. Ive tried setting the collider of the preview to a trigger but now its not working as expected
void OnTriggerStay(Collider collision){
isColliding = true;
}
void OnTriggerExit(Collider collision)
{
isColliding = false;
}
what is not working ?
should probably use a physics function for this though tbh
isColliding is always true
what is it colliding with?
nothing as far as im aware
Debug.Log(collision.name)
the code is exactly the same as when I used OnCollisionEnter
alright
oh apparently its colliding with the ground for some reasno
ill figure it out
Null my background is looping perfectly but I still have 2 problems. My background is shaking when the cinemachine is tracking the player and after 2 or 3 random generated tiles they just appear behind the background. any suggestions?
thansk for the help
not sure, show video of the problem
may take a while do you want me to send it in this chat here?
hi : D
I need to assign a component to a gameobject, but idk how
my class is Drag, instead of adding a new drag script i want to assign a existing drag
you want to reference a existing script in other object?
yes
public Drag drag
then assign it in inspector just like how you assign transform etc
i can't assign it via code?
you can
by find desired object then get component
what did u set camera to ? show inspector
looks like objects are moving behind the camera or something
can you show a example?
what about virtual camera
does the z positioning move while this issue happens?
idk how you will find the GameObject that have Drag component.....
nope
i have the Drag class on the camera
when i click i cast a point collider
if it hit something add the drag to the gameobject
what i'm trying to do is basically this
make sure.
what did you change when this happened?
I just tried to deactivate the cinemachine camera thing and it worked. Obviously the camera wasnt getting tracked anymore but My background wasnt shaking
if the hit.go have script that has Drag property:
hit.go.GetComponent<script name>.property name=this
weird. unless you had a script for camera don't see where it would be acting like thqat
i have a list of Vector2Int i want to save using newtonsoft, but for some reason it saves the magnitudes as well as the coordinates, even though i only need the coordinates, is there any way to stop it from saving the magnitudes? ```"coords": [
{
"x": 1,
"y": 1,
"magnitude": 1.41421354,
"sqrMagnitude": 2
},
show script you use to save
settings.NullValueHandling = NullValueHandling.Ignore;
settings.DefaultValueHandling = DefaultValueHandling.Ignore;
string json = JsonConvert.SerializeObject(DataManager.Instance.Data, Formatting.Indented, settings);
using (FileStream stream = new FileStream(savePath, FileMode.Create))
{
using StreamWriter writer = new StreamWriter(stream);
writer.Write(json);
}
what about layers?
nah why would layer effect it
Hello, I would like to Invoke my onInteraction event but it isnt invoken... can anyone help me please?
hold up background isnt shaking anymore. I just set the layer lmao
so whats in DataManager.Instance.Data
all the data i need to save, a lot of stuff
is the trigger even running ?
i have no problems with saving any of the data, the problem is it's saving the magnitudes of my lists of Vector2Int when it doesn't need to
yes it is... I tested it with the debug
idk unity event much
but i guess you need "IntDrive."onXXXXX
u see
the interaction class add it function to the oninteraction of intdrive class and once the GO that inherit the intdrive ontrigger , it invoke all function that added on it onXXX include the function in interaction class
I tried to put a breakpoint there and it doesn't jump there
null thank you for your help I found the mistake ❤️
so intdrive.oninXXX+=(this.)OnInteraction
Oh wait... why are u subscribing to the static event on its own class..
@cursive ember Try IntDrive.oninteraction+=OnInteraction
should be IntDrive.onInteraction += OnInteration
cool
what was it
Oh yup thank you
But i'm confused a lil
Why intDrive?
Layers lmao hahahah
you don't know your own code?
oh that's odd... ok at least it works then
you need a class reference see my previous explanation on above
Scrolling texture or shaders, both work fine.
I thought I want to call Interaction from IntDrive 🤔
yes so you subscribe the function to the oninteraction variable in IntDrive class, so you need IntDrive.oninteraction to specify the variable is a static and it belong to IntDrive class
I would need to do that in a Sprite or a RawImage?
Do I need to program the scrolling effect too, or is it an already existing feature?
Im working on a game can someone tell me why the player goes through the platform i have the layer and box colider 2d correct im just really stumped it might be something with the code but i was just hoping one of you could help me
Your collider is disabled
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
oh...
im new to unity so i didnt know
ohhhhh i see now
thanks
do i need something for jump like a input action file for the jump
I would need to do that in a Sprite or a RawImage? Do I need to program the scrolling effect too, or is it an already existing feature?
Yes, you would need to program the scrolling effect with the passage of time. You do need to create a material for it so you can change the Y offset of the diffuse map.
Sprites will work fine
The main idea is to create the material -> assign it to your sprite renderer -> Reference the sprite renderer in your code and access its material properties from there
I haven't done that in a long while so I could be wrong, but that should work as a starting point for you to look into
Alright, thank you
I'm new to Unity so sorry for asking dumb questions, is this it or it's an unique 2D Material?
That's it, you can change what type of shader it will use once it is created
I see, once I apply a new Material to the SpriteRenderer it disappears
I haven't touched anything regarding Shader yet though
Not sure even how to start messing with that
is there a better way to detect if a sword hits an enemy than OnTriggerEnter or does that method do just fine?
that sounds very reasonable to me
There's a number of factors that could be making your sprite disappear, the sprite renderer component tends to not work too well with shaders not meant for 2d, start with that
Remember, once you created the material you can select it in your assets folder and in the inspector you will be able to change its type
This is happening
The color changed, I guess it's supposed to do that.
But now it only appears below my game, even with the highest index
I mean order in layer
If the color changed it means you are using a lit shader, see if you can find unlit
I am feeling dumb now
Shader: Standard <--- change this to a 2d unlit type
Standard Unlit?
That should work, but there is a 2d category too with its unlit version iirc
Thanks, that fixed the color issue
Now I need to figure out how to make it show in the screen
Jesus, configuring Unity is HARDER than programming on it
@maiden owl Don't crosspost. This isn't a coding question, either.
Mb
That's true, #🔀┃art-asset-workflow is the most appropriate channel for that, then when all that is properly displaying you should look into this to have an idea of how to make it scroll: https://docs.unity3d.com/ScriptReference/Material-mainTextureOffset.html
Hello there, how do you handle commands with multiple args ?
For now i have a CommandModule with a dictionnary<string,Action> that register commands and can apply it but, what if i want to register GiveItemToPlayerCmd and ApplyBurnStatusBasedOnTheInvokerCommand ? They can not have static values set at design time
To give more context :
My player can hit targets with 2 types of sword, NormalSword and FireSword, the normal sword deals damage and the firesword deals damage and can burn with RNG. Each deal damage is based on the Strength property of the wielder and the Burn is based on RNG less the Defense property of the defender
If anyone can light up my path, he/she will be rewarded with fame and glory
I managed to script the Y offset part, but the Image is small
How do I make it to clone itself?
This is the image size lol
Go to your sprite, change the wrap mode to repeat -> scale up the sprite in your game and change the tiling size in the material's properties. You can still do it by code but I don't see why this part would be needed, only the scrolling is really needed to be done by code.
There's no size in the material's property
The wrap mode was already in repeat by the way
You are using textmeshpro, that's wrong
You want sprites / default
my approach probably cant help you:
for command with or without args, i normally use two pointer to split and check whether this command is valid (since i handle string or char* in c more frequently than in c#)
and it can take the args depend on whether this command have args or not and perform action
@digital fern
Ah, I searched for 'sprites', but I get what you mean now
Alrighty, it's now at Sprites/Default
I still can't find a tiling size option
Oh right, I had forgotten about that
ie if i have two commands: A; B <number>, i will check the first segment of command is "A" or "B" then if it is B, i will get the number @digital fern
Even with repeat it doesn't keep repeating, probably because of the Tiling size thing
@maiden owl You need to change draw mode in your sprite renderer to tiled
And this is still an #🔀┃art-asset-workflow question
a.
Then you can change the size in the sprite renderer itself
You can just do what that warning is telling you to
@scarlet talon I can't thank you enough for helping me 
You are welcome! Does it mean you got it to work? @maiden owl
I could have been more eloquent but that texture scrolling is something I haven't done in ages so my memory was all fuzzy
Yeah, it is working now thanks to your help!
You was correct all the way through, sorry for asking dumb questions :p
No such thing as dumb questions!
@scarlet talon Just letting you know, Sprites/Default doesn't seem to work when trying to change the mainTextureOffset, when I changed back to TextMeshPro/Sprite it worked fine!
SpriteRenderer.material.mainTextureOffset = new Vector2(0, Time.time * ScrollSpeed);```
This is the code if you are wondering
I see. Well, I'm using the URP rendering pipeline and its 2d shaders work fine for scrolling the texture
Might have something to do with the default sprite shaders then that won't let that be changed
By the way, this is not the only way of achieving this result. You could also use the parallax tiling technique for moving the sprite to give it the illusion of scrolling.
I see
In my playercontroller script I have a float called DamageToDeal how would I access that variable from my attack script so I can send it to the enemy?
{
private void OnTriggerEnter(Collider other){
if(other.gameObject.CompareTag("enemy")){
HealthComponent enemyHealth = other.GetComponent<HealthComponent>();
enemyHealth.TakeDamage(DamageToDeal);
}
}
}```
Thanks for your reply
Can't you have a reference to your playerController script in Attack ?
public CustomScript custom;
custom = GetComponent<CustomScript>();```
Hi i have install problem
It's been over 6 hours and it's the same way!
@dawn anchor probably just cancel it (in the 'x') and close it all. Maybe try to find where the it was downloading to and delete those files too.
Then just retard PC and try to install again. Probably will work out
Funny but works, always the same 'Have you tried restarting it yet?" xD
I tried all of these methods but same problem
Knowing that the Unity files were in the hard C and I transferred them to the hard E
It may be the cause of the problem
hmm, that might have created an issue yh
can you not just install it and install it again?
unity hub and stuff
just make a backup/save the projects you have somewhere and try to erase everything
@dawn anchor
already i did that
Maybe the hard E has a problem, so I will switch it back to the main hard drive
What is the best/correct way to access prefabs in static methods?
Hey, new with 3d attacks. Any1 know a good way to make the collider that deals damage appear when the enemy animation raises the fist?
https://www.youtube.com/watch?v=mkErt53EEFY
Just add a box to the fist with the collider and to trigger when hitting the enemy
Alright, Hitboxes... Learn how to make them, and how to program them in Unity in the next 3 minutes!!!
If you enjoyed this video, I have a small 1$ Member perk available for anyone who would like to help us save up for Facial Motion Capture :)
(Just click the "Join" Button next to "Like"!)
https://www.patreon.com/RoyalSkies
Twitter at: https:/...
is there anyway to follow the fist? its animated so I cant really track any transform that i know
unless i can track the transform of the bone
well, I suppose the animation is running on some top of body, that has a hand for example, just create it there. Put up a screenshot of the entity you are animating, the prefab I guess
{
int rotation = 90 * newPlayerId;
Debug.Log("rotations is " + rotation);
GameObject go = Instantiate(playerBoardPrefab);
go.GetComponent<NetworkObject>().Spawn();
go.GetComponentInChildren<RectTransform>().rotation = Quaternion.Euler(0,0,90);
Debug.Log(go.GetComponentInChildren<RectTransform>()==null);
}```
what am I doing wrong? The prefab instantiates but the rotation isnt happening
any way to check if a collider onTriggerEnter is a Box or a Sphere collider?
do you even know which object this
go.GetComponentInChildren<RectTransform>().rotation = Quaternion.Euler(0,0,90);
is acting upon?
the instantiated one right?
no
its a prefab with a child object that has the component
Box and Sphere are just derived classes of collider, so you'd have to check against those
What are you expecting? The rotation would always be z=90 on whatever that GetComponent lands on because you don't use your rotation variable at all
yes thats the thing
the rotation is 0 xD
I said it to 90 to test it but forgot to change it back but even with just putting that in it doesnt do much
set a breakpoint, look at the resulting rotation. If it's z=90 after that and then 0 at the next frame, something is modifying it and you're looking at the wrong thing
GetComponent<Collider>().GetType() == typeof(BoxCollider) ?
Ive been trying different ways but this one doesnt even work xD
wow I didnt knew there was "is" for bools, cool. Ok this one works but I realized new problems hahaha, thanks!
yup
Define "legit"
If it ignores its own collider
It's checking if col is attached to the same GameObject as this script yes. But if this is in like OnTriggerEnter it will never happen
It's in function Explode
Like deal damage to all others col except its own
You cannot collide with yourself
If you're using OverlapSphere or something it's reasonable
Unless, you're using Overlap* methods
Im using that
Hey all, can someone help me out with something?
I want to make a static function in a class that will spawn a rock (for example), and I have the prefab for it, RockPrefab.
The problem is when I want to spawn the rock (instantiate new gameobject) in the static method, I need to get the RockPrefab.
What is the best/correct way to access prefabs in static methods?
I tried making a static variable in the class and give it the RockPrefab but it didn't work 😦
Should I make a class to contain all important prefabs for the probject? Kind of like a collection I guess.
Maybe create a spriptable object with all the important prefabs?
Thank you for the help in advance ❤️
quick check, x <<= 2 is equivalent to x *= 4 right
you could have the static spawn function take a prefab as an argument. Then in the place where you call it pass a non static rock variable
ty
anyone know why when I go into full screen mode my photo attached to a cab gas doesn't appear but when I'm non full screen it does
class MyClass : Monobehaviour
public List<GameObject> gos; //fill in inspector
public static List<GameObject> gameObjects;
void Awake() { gameObjects = gos; }
then just use
MyClass.gameObjects to access
bit of a general question, how unwise is it to code in an unsafe context in unity?
if you do not know exactly what you are doing, very unwise indeed
the whole point of C# was because people were too lazy to learn how to program in C/C++ properly, hence GC
ah
my application was having a class's array point to another class's one, instead of copying by value
I was thinking pointers since I have a basic understanding of coding with them in C++
I can probably find a workaround though
but if they are arrays then they are in managed memory which can be moved unless you pin it
pointer into managed memory, very bad idea
Idk why u would need a pointer anyways
I call GetComponentInChildren but it uses the component the parent what am I missing
Use GetComponentsInChildren and skip the first element if u dont want the parent
you are missing having read the documentation
It really is an unfortunate naming convention though. I think everyone assumes what it does and is wrong at first
oh it also includes the gameobject
dam
its a dumb name in my defendse but I get the usage
thnx
why anyone would use an api call for the first time and not read the documentation about it is beyond me
ok, but when I call the function I need to give it the prefab.. and the question comes back again which is how can I store/access prefabs that I know I will use a lot, like that rock for example
did you not see my code example?
responding to it now
I guess this was the idea I had at first.
- make a gameobject that is a singleton and just put in a lot of references in it to the prefabs
- access that singleton gameobject and get the prefabs from there
But this way I always need this gameobject to be instantiated. It doesn't feel right..
Basically I wanted to do something like this:
public static class PrefabCollection { GameObject prefab = Resources.Load("prefabs/prefab1", typeof(GameObject)); GameObject prefab2 = Resources.Load("prefabs/prefab2", typeof(GameObject)); }
But instead of doing it so RAW and unsafely, I wanted to put these in there through the inspector.
You could use an SO for the same thing without instanitating then
then use Resources.Load if that is what you want
but that uses strings. It's a terrible idea to use strings for loading a prefab.. 😦 in terms of security and long run problems
Use SO and SerializeField to drag in from the inspector
even with an SO he will still need an instantiated gameobject / monobehaviour to access it
I just meant to get away from singleton
yh, I guess that's also another solution (currently kind of trying to do that and see how it goes)
The obvious answer is a static class, but you still need to find a way to populate it
I dont really see why having it instantiated is a problem though
Having objects in your scene to act as managers is extremely common
SO would be the same as a static class in this case, just being used as some collection of objects. Something is going to have to be instantiated to actually spawn these objects
I have some already too, I just thought that there was some "simple" way to get this done since all I want is literally a list of prefabs that could be accessed through all the project scripts 😦
yeees!!
public static class MyStaticClass
public static List<GameObject> gameObjects;
class MyClass : Monobehaviour
public List<GameObject> gos; //fill in inspector
void Awake() { MyStaticClass.gameObjects = gos; }
Oh if it's just to access not to spawn then sorry yea static is fine
I guess spawning doesnt matter
hmm
I get the idea, sounds good. I guess the "way around" I have to do is exactly a way to populate the static class
Regardless tho SO will allow you to create many assets of this, each with their own custom list of game objects rather than a static class for each one
In the inspector, its public
MyClass populates MyStaticClass and you populate MyClass in the inspector
sorry, couldn't understand what you meant by this, im dumb
is there some open source library / functionality in C# to test a string for whether it's semver or not?
ofc I can write myself, but is there something existing?
1 moment I'll type some example on pc
I am thinking that this might cause a problem though..
The game kind of "has to run" to populate the static class :/
indeed, but why is that a problem?
Sure, Version.TryParse() (namespace System). Note that it has a major.minor.revision.build format, you'll have to fail if a build number is specified
im asking myself if that might not be a problem in terms of some sort of script running before the "populate" happens, and finds no prefabs there, or something like that.
I guess I have to be careful to always call the static function only on Start()'s
you just make sure MyClass has a very high execution order, i.e. runs before anything else
can't really wrap my head around how do I use it
Like any other method implementing the "TryX" pattern
not sure I know what that is. Are you refering to stuff like Awake > Start > FixedStart > OnTrigger > Update > etc?
Pass a string and it returns a bool whether it converted successfully
Optionally, you can get the version in a variable using an out param
No, check out the unity documentation on Script Execution Order
it wants me to pass in Version object, I dunno...
ah, it's out, okay
oh nice, exactly what I was wondering that Unity might have 😄
Yeah, that probably solves anything related to the worries I was having with this
You can discard it if you don't need it, .TryParse("", out _)
but does it comply with semver? it doesn't mention that
Scroll up, I mentioned what format it accepts
yeah and I also need to accept things like .pre-54
From what I see from the semver spec, not all is accepted
Nah that doesn't accept that
Roll your own

using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "ExampleSO")]
public class ExampleSO : ScriptableObject
{
public List<GameObject> gameObjects;
}
then you just right click create whatever u choose the menu name to be. Then you can just populate the list in the inspector
u can split it up then, have one for characters, projectiles, etc etc whatever u need
- Thank you for the time and elaboration of your demonstration to help me ❤️
- I am still thinking on the subject but yeah, I like the idea of doing some sort of system using SO in the matter you are explaining so that I can easily make divisions between stuff like resources, buildingblocks, etc
- The only problem I see with it (I think it's solvable, not sure how yet though) is how do I access those scriptableobjects? In the case you show, 'characters'.
You just plug them into whatever class needs them
U can do it in the inspector too if its known beforehand what objects need these
wait, this doesn't work with static functions though..?
SO can have functions
my mind if a bit of a mess tbh .-. I never used static functions a lot tbh
Idk what the static function is for though
For example, in my case:
- I have a prefab DroppedItem that has it's own class DroppedItem.cs. It is what it sounds like, it's a dropped item that is pickable and makes a little animation going round.
- I wanted to make a static function in DroppedItem.cs that would spawn one of these DroppedItems. But for that I need to get the reference of the prefab DroppedItem.
ok actually I found this regex and it seems to work:
^(0|[1-9]\d*).(0|[1-9]\d*).(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-])(?:.(?:0|[1-9]\d|\d*[a-zA-Z-][0-9a-zA-Z-]))))?(?:+([0-9a-zA-Z-]+(?:.[0-9a-zA-Z-]+)*))?$
it tests string against semver (it's from semver website)
jess, that's a long regex xd
although they don't mention it as C# compatible (I dunno if it matters at all)
U can use regex in c#...
https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string:~:text=buildmetadata)%20that%20is-,compatible%20with,-ECMA%20Script%20(JavaScript
they specifically mention some languages, that's why I'm concerned
Ah, you will need something else that declares when it should drop. Since the SO wont live in your scene
here if you dont believe me its natively supported with methods
I believe you lol, I just used this method to test it
what I asked is does regex care about language
or it's the same everywhere
it's like a universal thing
okay 🙂
yeah. In summary I want to make a static function in DroppedItem to replace this code.
This code is called in an item spawner. And there will be similar code in many places. As you can see I pass the '_droppedItemPrefab'. So in the spawner I have to have the reference to that prefab, which sucks. And so will any other class that wants to "spawn"/"drop" an item.
So to fix this, I wanted to make a static function that would make this code
you can still make that static, but something is going to have to call that function
thing that bothered me is that they specifically listed some languages, so I thought maybe it's dependent on language, but thanks for clarification
do mind there are variations
like how different dialects of the same language
You'd have to check as regexes (is that how the plural form is written?) have flavors so no, not all the regex matchers out there support the same features and might have different syntaxes
if you want .NET specific ones then it's here
https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference
https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string:~:text=version is “1.2.3”.-,Is,-there a suggested
from these two, which one is more relevant to use in c#?
I have no idea
Yeah, and when that static function is called, I wanna pass the item that will drop, so DroppedItem.StaticFunction(Item itemToDrop) something like this.
And since the freaking droppedItemPrefab will ALWAYS be the same.. it makes no sense for me to have to pass it everytime
You can easily check by using something like https://regex101.com, pasting the expression, and switching to the .NET flavor on the left bar menu
oh thanks
i love that site
If you have some test cases, it even supports that!
stealing this
you can still store the game object in a static field
okay it says error for one of them, so yeah it helps, I use the second one
thanks a lot
basically make this @lean sail
Compare with .net and pcre if you want. But the error is from ?P in the first one
https://www.regular-expressions.info/refrecurse.html
weirdly it says no match with "1.1.1"...
u would need a static field to store that _droppedItemPrefab which u can do
what the fk is going on...
yeah, it worked.... HOW THOUGH O_O I literally tried this the first time
and it said something about blablabla using static field in static class or wtv
couldnt
oh well
o-o
well idk how u populated that but it should work
i have .net selected as well
well yeah, that is the ONLY issue, I cannot give it a value in the inspector xd
BUT @lean sail , fortunately I have the perfect workaround
OdinInspector: odin static inspector ❤️ ❤️ ❤️
OdinInspector: odin static inspector ❤️ ❤️ ❤️
okay, I'm dumb. apparently when I select the line with triple LMB and Ctrl+C it, it copies something wrong
probably newline character
yea that regex really doesnt have anything too complicated, i wouldve been very surprised if it didnt work in .net
regex is actually a super powerful thing. it probably doesn't do anything crazy other than just iterating over string and checking for the pattern, but it eases out everything
I was literally about to write my own library to test strings for PascalCase, kebab-case, semver and so on, but now it's so easy
i believe it uses a state machine, been years since ive actually looked into it though
@lean sail I am currently trying to iterate a solution based on what you said, I will give you some feedback once I am able to do it. Thank you so much for the help 🙂
You too @knotty sun
Hey, I have this simple code:
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "EnemyArma"){Debug.Log("hi");}
}
in a script inside an empty with a collider, but it doesnt work. The tags are fine, colliders are getting inside, but only works if I put it inside an empty with a Character Controller
not with a Collider Trigger
It only checks for that Character Controller and it works, and I dont know why
OnTriggerEnter works with every other object, but this is the only scenario where it doesnt
can someone help why cant I pass nulls in the function?
you probably can.
Check if you are not doing slots[null].item.
Run that code with debugger and you will probably figured the problem out faster
@vocal root check if the tag is in the correct gameobject, basically if the gameobject that has that tag is the one with the collider in it.
Regarding tags, I dont recommend using them because they use strings and that's a really simple way to spend hours looking for an error that is in a string. But if it's just a simple project dont sweat about it tbh
what debugger?
tags are correct, its one of the first things i checked over and changed to try other things
whats the error say, and which part specifically is null
id really hope their int isnt null :p
He shouldn't** need to. If Item is an Object, it can always be null
yea scriptable object
search online how to use debug with Unity. 'Simple' problems like this will be a LOT easier to know why they are happening and fix them
is this what you meant? ima be honest ive never seen this before lol
uh if its not needed with unity objects then u wont need that
ive searched it up i cant find anything
only jetbrains
where are you writting your code?
Visual Studio?
VS Code?
is slots itself null, is slots[index] null, or is slots[index].item null
Visual Studio by Microsoft has a lot o annoying performance issues. To get rid of them I suggest you to switch to Visual Studio Code instead of tilting at windmills. The video contains tutorial how to setup Visual Studio Code to work as Unity external script code editor.
--
My GitLab: https://gitlab.com/better-coding.com/public
My Blog: better...
theres a big difference
i mean if slots[index] was null the rest of the script wouldnt work lol
well u cropped to only show a screenshot of 1 line..
yea sorry
also just paste it with !code blocks
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
its small enough
ah alr
this is stupid tho cuz id have to make a shotty work around instead of having a nice clean function
ill try this
https://rebane2001.com/discord-colored-text-generator/
Made me think, and just found this
Rebane's Discord Colored Text Generator
is player null?
i just think that because equip item seems fine, the error wouldve been in EquipItem itself if you actually passed the null value
but yea debugger probably wouldve found that for u
🧠 i am my own debugger
i mean
before setting the player*
lol thanks I wouldve been stuck on this for so long
np
Definitively it just checks the collision with a CharacterController, even changing the tag, no matter what I do, only detects the Character Controller Collider
for some reason
Theres no way this, even using a different tag, just do the thing when colliding with a Character Controller
{
if(algo.gameObject.tag == "ColliderPlayer"){Debug.Log("hi");}
}
Cant understand
The other object needs a Rigidbody along the collider. If that still does not work follow the troubleshooting guide at https://unity.huh.how/programming/physics-messages
omg thank you, that worked
I am wanting to make a more complicated character controller, one which offers combat in air or the ground, basically you can do combat in other states, getting to the point I have made character controllers in the past using state machines, but I was wondering if there is a better structure to use for this idea, considering with a state machine, as far as I know, there is 2 options, one i build combat into each state, or 2 i layer another whole state machine onto the character to blend combat in. I have used the layer method before, but it gets messy having to go over every state 2 times +. If you have an idea @ me
You can use the Unity Animator as a state machine, and use its built in features
In terms of scripting, that would just fall into the build the combat into the main state machine correct? because either way you would still need a way to activate combat, and also be able to switch between states, calling the different layers of the animator nonetheless
What you're describing is kinda vague, but i dont really see how this would be an issue at all. It's just no longer checking if the player is grounded when allowing them to do certain actions
Also not entirely sure what starting combat means, do u mean like a pokemon fight, or just attacking?
The thing that im describing is using another way to structure data, while comparing it to a state machine.
"It's just no longer checking if the player is grounded when allowing them to do certain actions", Here i believe you might be describing a controller where it is kinda all in one script, type of thing, rather than a state-based controller. Using states makes it easier to structure the character, and it makes it easy to add on to a character, its just i am looking for a way to implement combat blending it with a normal movement state machine. So it wouldnt be so much a problem to know when i can switch to combat, but also figuring out how to blend combat into a normal character controller, in a efficient way
"Also not entirely sure what starting combat means, do u mean like a pokemon fight, or just attacking?"
My goal is somewhat like a theme park design, where you can only attack in certain zones, so it is not like i plan to always allow the player in combat, in this case starting combat would mean entering an area where you can use combat
I dont think state machines should be used as a player controller unless this is some very very niche case where the game design actually fits it.
State machines for this are going to be a process of hard coding every single step while not bringing any advantages
While its a rudimentary solution, I would draw out your state machine ideas first, and see what "looks" better. "looks" is a crued metric, but it can help with the underlying logic flow.
They're also going to be very fragile
That kinda brings me to the point, where i was wondering if there is a generally better accepted way besides state machines for complicated character controllers
Idk if theres even a name for it, but just process the inputs as they happen. If the player clicks to attack but isnt the right area, then dont allow the attack
Doesnt have to all be in one script either
Given that i have drawn it out before, sometimes you overlap, before when i experimented with the idea, i did animation layering for the base states things like walking and jumping, just changing the animation, but that would still leave the issue of all the new states you have to add, which i had heard before that it would be best to just layer a "combat state machine", which just made me wonder
Adding more state machines wont fix the main issue, itll just make it less fragile
You can have a state machine if your combat system specifically needs it, but with what you described it really doesnt seem like you do
The state machine would just be an enum lol
Does anyone know how to turn a double into a float
people are literally actively responding to u in #💻┃code-beginner
float val = (float)doubleVal
How'd you get the double in the first place? Just curious 
System.Random
you can get random floats with unity
Oh, well Unity has a Random class as well 🤔
Didnt think you could use ranges with unitys random namespace
You could even seed if needed. Here are the available members: https://docs.unity3d.com/ScriptReference/Random.html
I wondered if anyone has any thoughts on how best to achieve a lazy lerp? For instance if I had objects lerp in a direction based on the mouse. And I wanted them to wait every few seconds or so before getting the mouses position again, while still lerping to the last known position. I'm assuming Coroutines. I was just hoping someone could psuedo code it out loud, because I'm not really sure how to approach it
while(true)
for(float i = 0; i < delay; i += Time.deltaTime)
movetowards target position
update target position
That simple huh? Ok, I'll try that
Actually, you'd want to wait..
would waiting interuprt the current lerp?
I suppose i could separate the mouse tracking from the lerp, and still use wait right?
using wait, on the mouse tracking, but not the lerp
Proper syntax might be like... cs for(float i = 0; i < delay; i += Time.deltaTime) { transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime); yield return null; } targetPosition = ...
i wouldve probably saved an hour if i knew this
Prospect for future development 
Documentation 🪄
classic XY problem as well, ask how to get a random float rather than asking how to convert a double to float
Something like this :
Black line is the ground (3d model or terrain)
Green line is raytrace/linetrace
red line is what I'd like to have
Yeah thats what I had in mind, just had to check.
I dont think theres anything like that builtin, you would have to mess with a bunch of casts yourself
One thing that can help here is using Vector3.Project to align the ray to the hit normal
And if you dont hit anything then try casting more downwards
What is the purpose of this?
was thinking a raycast down would be good
lookup hovering tuts they cover it
you can get similar result
apply force opposite of ray dir
sum like that
Its easy from one position. Along a line is trickier
well you would have to be hovering the raycast you send which is easy, but sending it consistently along the terrain shown in that image is going to be tedious.
You'll need some distance to fine tune so you send a small raycast in that direction, then cast downwards to see where the next raycast should be at (height) and where to shoot (hit.normal)
its not the same as just hovering an object
the further the distance, the less accurate but less laggy this is
With mesh colliders you could also potentially utilize the mesh data (and hit.triangleIndex) directly
i too am curious though of the use case, this seems extremely niche
Yup, that's what I have in mind, some burst of short casts and check down casts
The purpose is to check if a position on ground is reachable by a character controller in a straight line, using simple cast could miss or give false result if the ground is not flat
Thanks 🙂 👍
If you are using NavMesh then there is NavMesh.Raycast
Which I use for my NPCs to check if some direction is reachable
It works with straight lines even if the ground is not flat
But yeah the limitation is that it only works on the navmesh so idk if its any help for you
Nice!
I'm planning to add navmesh for my enemy's AI, so yeah, this would be helpful, thanks again 
what does this mean: NullReferenceException: Object reference not set to an instance of an object
Attack.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Attack.cs:14)
{
public playerController playerController;
private void Awake() {
playerController = GetComponent<playerController>();
}
private void OnTriggerEnter(Collider other){
if(other.gameObject.CompareTag("enemy")){
HealthComponent enemyHealth = other.GetComponent<HealthComponent>();
enemyHealth.TakeDamage(playerController.DamageToDeal);
}
}
}```
am i not accessing the float correctly?
check if the HealthComponent on other.gameObject is null
other.gameObject cant be null so probably the former
Note that other.GetComponent will get the HealthComponent from the object that has the collider
If the collider is on a child it will not work
You could either use other.GetComponentInParent or if other.attachedRigidbody is not null then other.attchedRigidbody.GetComponent
@severe falcon
there is also a collider on the child so ill use other.GetComponentInParent. thx for the help
Is it possible to take a specific kind of component and edit that component for every object in a hierarchy?
Like, I want to edit the base map of every object that has a material component.
I'm trying to avoid individually referencing every object that has a material in scripts.
Material is not a component.
Aside from that, yes, it's possible.
Yeah, you probably want the Renderer component and then access its materials
Hi all. How to AddListener a method to an event on Awake() or Start() but it require some parameter?
"the" renderer component? Where can I find that in the Inspector?
So the require parameters would only process on that method, but I need to AddListener to the event on the beginning of the game
Aren't you doing this via code?
You said
take a specific kind of component
That component would inherit from Renderer
Oh actually, disregard
All renderers have materials
Are you talking about UnityEvent?
Ok I see now. Thank you. And manipulating this will allow me to effectively universally relatively change all object's base maps?
As long as you use renderer.sharedMaterials (and not .materials, which will create copies of them), you can modify those materials and the changes will be shared with other materials of that type
I'm still not 100% sure what you are doing. Is it like an editor helper script?
Yes
As the doc says it cant take arguments
@deep lantern Look into System.Action for delegates that can take parameters
No. I actually don't know what that means. You know how objects redshift/blueshift if they're moving away/towards the observer? I'm making that happen by getting the player's velocity and I want to proportionally change the base map's red/blue values accordingly.
Oh alright, thanks for the answer Osmal
I'd do post processing, but that doesn't work for objects that move independently to the ground.
You know how objects redshift/blueshift
Not really familiar with this phenomenom but I get that you want to change each objects color individually based on distance? Or speed?
Speed
So, I was thinking that I could get away with just changing the renderer settings or whatever for environment objects and just manually do it for "dynamic" objects.
I still dont quite get what the final result should look like so I can't give meaningful tips
I would probably use a custom shader and a global color property or something
Changing the material property should work. Might not be as optimized as a custom shader though.
Thank you very much! And in case you were curious (if it were to gradually change directions, it'd go through the color gradient before becoming completely blue/red):
the wavelength is increased/decrease but the factor is 1/c...
I know. I just had to figure out how to link the math to actual results on the screen.
maybe you need to multiply the delta change to emphasize it effect..
Haha no! I'm gonna lower the speed of light
how should i get the GameObject that my Physics.RayCast hits?
Should read the raycast documentation
It'll tell you
ah
just putting this here for future reference, public static bool Raycast(Ray ray, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
started learning regex syntax 🤣
im still confused
RaycastHit doesnt have a .gameObject property or anything
just a .collider and .rigidbody
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html#:~:text=of the object!")%3B%0A%20%20%20%20%7D%0A%7D-,Declaration,-public%20static%20bool
i dont know what version of Raycast you're using
but there's one with a RaycastHit out variable
yeah but .collider has .gameObject
ah right, im dumb lol
thanks
hmm.. im trying to do Debug.Log(hitObject.name);
but i get a nullreferenceexception when nothing's being hit
so then i put it in an if statement to check if hitObject.name == null
that's expected?
but my IDE is telling me that's always false?
i was still typing my issue, sorry
show your code?
yeah show code
it's weird for IDE to show it's always false
cause it's from out variable
just where you do physics.raycast
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.down), out hit, 200))
{
impactPoint = turretPos + transform.TransformDirection(Vector3.down) * hit.distance;
}
else
{
impactPoint = turretPos + transform.TransformDirection(Vector3.down) * 200;
}
GameObject @object = hit.rigidbody.gameObject;
if (@object is null) Debug.Log("null");
else Debug.Log(@object.name);
please dont use is
use ==
oh ok
im used to using is for comparing to null/constant values in normal c#
there's something about how Unity objects are null checked differently
i heard somewhere that it's faster or something?
or works better than .Equals() for strings or something? cant remember
is operator doesn't work with gameobjects
== null is the safest
use ==
ah ok
ah
this is really weird, but with gameobjects and monobehaviours use ==
can i make the GameObject nullable
GameObject? @object = hit.rigidbody.gameObject; like this
That wont help anything
? it's nullable already
Even if it did work
by virtue of being an instance of a class
huh, weird.
The functions that take the game object wont like it, and itll break
how come im still getting NREs then?```cs
GameObject @object = hit.rigidbody.gameObject;
Debug.Log(@object == null ? "null" : @object.name);
because.. hit might be null?
why dont you check it inside the if statement
You are trying to get the game object of something that is null, then checking if that object is null
your Raycast returns true if it did hit something
?
but the if statement only gets run if the ray is hitting something
also are you sure you want to use .rigidbody and not .collider?
oh, whats the difference?
check for hit.rigidbody.gameObject
inside this
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.down), out hit, 200))
{
impactPoint = turretPos + transform.TransformDirection(Vector3.down) * hit.distance;
}
the difference is that nobody guarantees it has a rigidbody
yes and only if it hits something then hit wont be null?
but if nothing is hit the code inside the if statement wont even be run, no?
then you do it inside else
never mind. maybe i'm not understanding the issue
i guess in my case all my colliders have a rigidbody so i didnt notice anything
good call tho
well then it doesn't really matter. but it means you just trust yourself that everyone has a rigidbody. in next project you will apply same code and it will blow up your computer
just use collider because that's what physics.raycast is looking for, not a rigidbody
yeah i changed it already
thats what i was thinking
although i think its just easier to surround my code in a try/catch
for my scenario
thanks tho
and in the future please dont crosspost
its just that i didnt know which channel to put my message in lol
you pick one
shouldve deleted my message in #💻┃code-beginner
I'd advise you against using exceptions as a thing in your game
ye
keep in mind that any exception you throw in built game = crash = mad email to you that game doesn't work
maybe i'll just do else { return; } and force the player to have a target in crosshairs before firing i guess
the projectile is supposed to be homing after all
oh
even if i try/catch?
Using a try catch when you just dont know what to do is a setup for failure. Yea your game wont have an error when you run it, but something inside that try catch didnt run when it was supposed to.
well try looks for an exception, it means it's already thrown if you catched it
so yes
You could try catch your entire game, but theres very good reason that no one does
ah ok
guess i'll just do this then, ty
Aren't exceptions really bad for performance?
Try catch is for when the errors are out of your control. Like searching for a file and the player deleted it
Is it just when you throw the exception or does just having try/catch itself introduce large overhead too?
@grim smelt in general - exceptions are not meant to be used for something that you know will happen
Try catch itself wont be any noticeable performance hit
alr
exception is something like you didn't get right format of data from an external database
something you have 0 control over
oh ok
The exception is going to be the heavier part I believe
What would be some keywords/patterns to look for if I'd like to research how to best implement multithread ING for some of my systems, i.e for Navigation or AI? While I do understand how to write multithreaded/jobs code, I'm not sure what would be the best way how exactly to design the architecture for for example moving the AI behavior logic to jobs.
I feel like simply starting a job for each single Ai instance is not the best solution, and would imagine that there are better patterns, just can't seem to find it. Because most of multithread tutorials are about basics of how to use jobs, not when.
I can imagine having some king of manager that the instances send work to (or that they subscribe to, and he iterates and updates all of them) , that is running on difrent thread. But I'm not sure if the overhead of having to send data between classes, especially since a lot of things need to be copied due to thread safety, wouldnt be worse than simply keeping it songlethreaded.
That's where the testing part comes into play. There's only point in using multithreading if the benefits outweigh the overhead.
pointer to array of struct
if you use task, then you can have managed object but you cant call unity api
if you use job and dont want to copy then use pointer
GameObject has initial x rotation set to -90, and when pressing Space button all 3 axes are changed
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
transform.Rotate(Vector3.up, 90f);
Debug.Log("rotated");
}
}
How do I change just rotation's y value?
you can google how to rotate object on one axis in unity
(-90f, 0f, 0f)
no, 3D
so the only way I have found is to make my prefab a child of another GameObject with Quaternion.identity rotation, cause there is no way to rotate just one axe I guess
Hi, I have an issue where scenes don't seem to completely reload after exiting to my main menu then returning to that scene. Some UI related stuff seems to be getting unassigned, any common reasons why this happens?
how were they assigned in the first place?
I tried both assigning through serialized properties and doing it through GameObject.FindWithTag()
somehow it's null either way
I'm having issues with events. I'm spawning in two of the same object and subscribing events to them. I placed a debug that shows that both of them have run the += Subscribe function. But now when i invoke the event its being called only from the 2nd of the two objects. and its also being called twice.
Event Manager
{
SummonFromDeck?.Invoke(card, isServer);
}
Subscribing to event
{
if (!SubscribedToEvents)
{
SetAbilityCardComponents(card);
foreach (var ability in Abilities)
{
if (ability.hooks.HasFlag(Hooks.SummonFromDeck))
{
Debug.Log("My Team Is: " + card.myMinion.Team + " My Network Id is: " + card.myMinion.NetworkID);
EventManager.SummonFromDeck += ability.SummonFromDeckTrigger;
}
}
SubscribedToEvents = true;
}
}
Event
{
Debug.Log("My Team Is: " + myCardComponent.myMinion.Team + " My Network Id is: " + myCardComponent.myMinion.NetworkID);
if (card.myMinion.Team == myCardComponent.myMinion.Team && card.myMinion.role == MinionRole.BL && myCardComponent.myMinion.status == CardStatus.Hand)
{
if (IsServer)
EventManager.RespondedCards.Add(myCardComponent);
Debug.Log("Summoned From Hand!");
myCardComponent.myMinion.status = CardStatus.Board;
}
}
i think so, the Debug.Log("My Team Is: " + card.myMinion.Team + " My Network Id is: " + card.myMinion.NetworkID); is showing different values
do the abilities need to be unique then?
so what do i need to do
Not entirely sure how to address the problem though, how exactly can i fix the issue
nope, normal objects. Yeah, they are still in the scene. At first I thought it might have been assigned to the prefab instead of the instance, but that is also proven to not be the case.
yes
it debugs twice the same mycardcomponent
the 2nd players one is doing a double call. As soon as i removed the card from the second player the first one gets called once
the game manager calls invoke and sends the card that was played to all listeners
I just tried now to make the abilities unique, but didnt change anything.
is there a way to track event listeners?
It doesnt matter which card i put in params, the 2nd player's card is always being called twice
the event is only being triggered on the second players card, if the second player doesn't have that card then the first player card will trigger
the minion of the card
I thought it might be a client thing, but the issue is happening on the server. so i assumed it had something to do with events that i dont know about
Yes
Yes if it has that ability
yes
the cardcomponent that is storred in the ability tells it its player
so how would you go about it
yes
the mycardcomponent is storred on the ability
So basically what im trying to do is. Give a minion the ability that if a specific card has been played then that minion gets summoned to the board. To do that, every card that is played is sending an event to every minion with that ability to check if the correct card has been summoned from the correct team. Then it will summon itself
ok that makes sense
so you place that minion card
then call sub with itself as param
and for each ability it should interact with, you add a listener...
and then when you invoke, it says which card has been placed...
ok that all makes sense, are you sure it's not the placed card's fault then?
if cards are both placed at whatever player, it means that myTeam is always true
no it makes no difference which player places the card or which card it is.
the placed cards team needs to match my own cardcomponnt team. but the issue is that the my own cardcomponent team is always player 2's team. it should be one from each
"But now when i invoke the event..
its being called only from the 2nd of the two objects...
and its also being called twice"
the 2 objects are the listener minion cards?
then it'll be the same function called twice
So the ability needs to be unique?
but i'm assuming each ability function is an instance because otherwise myCardComponent would be the same
the minion is its own instance but idk if the abilities needed to be aswell
where are you getting myCardComponent then
ill try making the ability unique before i add the listener
the gamemanager assigns it
but if ability isn't a unique instance then it just overwrites it
maybe thats whats happening
when i build the android application the previous version remains and isnt getting updated, what could be the reason, used pun2 there and now using netcode
Works now Thanks @twin hull
😭
😆 I didnt think abilities needed to be unique if the Minion itself was
If you do build & run it either doesn't detect your device(in which case there would be a warning message in unity) or you don't confirm the installation on your device(you will get prompted wether you want to install an app after it's transfered to the device) and the time runs out(it's only visible for like 5-10 sec).
not doing build and run
building then sharing via whatsapp or dirve
It doesn't belong in here. And you can't make it writeable. Or rather there's no point in doing that, cause unity would reset any changes don't to packages.
is there a way i can copy any one channel from a Texture2D to another channel of the same texture in script?
i've tried googling a little but havent found much yet
from what i can tell i need to do GetPixel to get the color of a certian pixel, then i can extract the value from a channel, and then use SetPixel with the modified color?
hi, im trying to create a character with a NavMeshAgent, i want the character to instantiate and fall from above but im having the issue that it obviously wont create the navMeshAgent from that hight, how do i activate/create the agent only when it touched the walkable navmesh?
Then no clue, but it's not really unity's problem at this point.
That would work
Messing with textures on the CPU side is pretty slow but if that's not a problem then use that
it shouldnt be an issue, its only for editor stuff. im experimenting with generating a texture from a font. or rather saving the font texture asset as a png i can use for other things
Yeah you can do it with the way you mentioned. Another alternative is using Graphics.Blit and a custom shader that does the work
Or a compute shader
But maybe start with the GetPixel stuff
yeah, i think that would be the simplest way to get something working to se if its worth expanding on
how would i go about rendering a sprite made from a sprite atlas into a png?
i tried something but i think its completely wrong as im getting/reading the wrong UV
ive instead resorted to setting up a scene to render screenshots to make textures of the different icons i need
How do I modify material property of an instance so that it doesn't affect all the objects which have that material???
Help much appreciated
if you change a material through .material property it will automatically create a copy
but the cleanest way is to use MaterialPropertyBlock
has anyone used NavMesh navigation in 2D?
Does OnDestroy event run when we do application.quit?
Hi. What is an easy way to cut a sprite along a spline and get 2 sprites as an output. I want to use the Dreamteck splines asset to draw a spline. But not the point. How to cut a picture along a curve?
what does this mean and how can i fix it?
it means you are trying to access an array with an invalid index. you fix it by using a valid index
in that line of code the index is invalid?
no
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
that looks like the entry in a try catch block
use this so people can see the full code other than a single png, jpeg, ect.
If you look a bit lower on the Stack trace it should show you the real source of the error
Not the exception
can help to come up with more solutions
tbh i have no idea what any of that means
i just function print error bro
you should ask who owner of asset, ask theme
Stack trace is the extra info that you see in the bottom of your console after you select an error
It has links to the code that caused the error, in the order it was called (from bottom to top)
it's a call stack, not a lot of help in a try catch block
this section?
you need to post your code using one of the methods shown above
you posted a single line of code. The line starting 'throw'
you need to post the complete try catch block
Call stack, stack trace, does it really make a difference here?
yes, because a catch will not show the origin of the exception
Is trace more for when it has crashed
Isnt it one of the lines in their latest screenshot?
we can only know that it has occured within the try catch block
I see, I'm confusing with something else
I rarely use try/catch and exceptions (I mainly use Unity C#)
I remember why now
Can't trace back to the exact line
yes, the actual line in error is being masked by the usage of try catch
so we can not even guess until we see some code
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
hey I have this code so when I hit an enemy I remove him -1 hitpoints, but when I collide I remove him every hit point. Any way to do it just 1 time? This code is in the update btw
bool hasHit = Physics.Linecast(startSlicePoint.position, endSlicePoint.position, out RaycastHit hit, sliceableLayer);
if(weaponSpeed >= 150)
{
if(hasHit)
{
GameObject target = hit.transform.gameObject;
if (target.GetComponentInParent<EnemyTakeDamage>().hitPoints >= 1)
{
target.GetComponentInParent<EnemyTakeDamage>().hitPoints -= 1;
}
@vocal root are you doing this in every Update?
yup
I know thats why the numbers are going down instant, so I need a way to stop when its done once till I hit it again
Depends on how the whole thing is structured, but you could give your enemy a cooldown in EnemyTakeDamage by having a timestamp of the last time damage was taken and if the current time is too close to that don't take damage again.
with a coroutine and another bool?
I have a large tileset image that I'm importing and I've set the sprite mode to multiple so every sprite is separate. Is there a way to add all of them at once to my tileset instead of manually dragging and saving every image?
No coroutine needed. In EnemyTakeDamage have a float LastDamageTime. Then I'd probably have a method to lower the health rather than changing the hitPoints var directly, so EnemyTakeDamage.TakeDamage(int amount) and in that method check the current time vs LastDamageTime.
There's probably a more efficient way to handle this, but without seeing your entire project its hard to know what way is best.
Ok the lower the health function is nice, should I add a cooldown number to that float and then lower that value with time right?
How can I make a sprite that's small easier to click and drag?
make the collider bigger?
I was trying to parent it to an empty game object but it throws the scale off. I'll try modifying the collider , but I'm using physics and colliders for collision detection
if your sprite has a script component(like your player) you can add larger children objects to grab mouse clicks and then use [SelectionBase] above the script class to make it so clicking on that object always selects the parent object.
so regardless of what I click on: the shadow, camera, or arrow object--it will always select the Player object
My sprite has a drag script , one sec I'll post
as long as there is a script component added to the object you want to take click priority, just add [SelectionBase] above the class in that script object
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
public class DraggableObject : MonoBehaviour {```
then just add a new empty gameObject to that object with a larger collider
if you don't want the larger collider to have an effect in game, just make it a trigger
hmm nevermind, seems it doesn't take colliders into consideration with mouse clicks
yeah I couldn't get a parent object to drag
added the script , collider , rigidbody 2d and nothing happened
you may have to do your own gizmo coding
oh dang I don't know anything about that
Anyone know why these weird lines are appearing in my tilemap?
Share a screenshot. But its probably tearing ( lines appear where the tiles touch )
is there any difference in performance between using out and returning a variable?
take the following piece of code, for example```cs
public static void Main()
{
Test1(out int x);
Console.WriteLine(x);
int y = Test2();
Console.Out.WriteLine(y);
}
private static void Test1(out int x)
{
x = 5;
}
private static int Test2()
{
return 5;
}
would one be faster/more efficient than the other?
i am not c# expect but i think out is something like pointer
usually referecing/dereferecing address is painful but you have no other ways to write code without like
I'm watching b3agz's YouTube series on making Minecraft in Unity3D, though for some reason even if I've been following it step by step, when rendering my chunk the faces on the sides become green at a certain angle..?
would raycasts work in any capacity?
With this texture it's clearer
I don't think so, you need some way to make the object grab mouse input. You may have to go macro on this and have some sort of deeper editor tool I'm not sure
This seemed to be an issue with mip-mapping and using an atlas
you try learn how voxel engine work. dont try learn some tutorial on youtube is dont help you
I mean my whole code structure is completely different than what the guy is doing, since it's quite inefficient
https://0fps.net/
learn here and research with you self no one can help you
Like I am knowledgeable enough in Java/C# where I am just using that to get a starting point
No need to give such a rude answer jesus
sorry im bad at english
i just share tutorial how made voxel engine and i want to said
"no one can help you" bacause voxel engine is very hard to do
what is that website even
So I change material Component of MeshRenderer every frame.
I don't really think that's great for game's productivity. Any way to change it somehow?
private void Update()
{
if (selectedItemRenderer)
{
if (Collides())
{
selectedItemRenderer.material = errorMaterial;
placedCorrectly = false;
}
else
{
selectedItemRenderer.material = selectMaterial;
placedCorrectly = true;
}
}
}
And yes, this script hangs just on 1 GameObject
you just make feature check if already material for place type
and dont change material it if that obj is already has material type
yep, so how do I actually do it?
use design pattern your code
or tutorial on youtube
I don't get it
maybe I should consider using WaitUntil?
if u dont know how to do right way
learn vdo on youtube
is have many and right way to design code
do you think I can find the exact video I need? does it even exist? 🙄
I do not highlight object
I am just changing its material
are u newbie code?
it depends on who you consider as a newbie code
if yes you should try learn it link
is have code, design pattern how to change material for right way, optimize
that's how to Highlight the object
so making a border
You could simply use a bool to store which material you set the last time. Then only change the material if the bool changes
oh.
If the point is to avoid changing the material when it is unnecessary?
Then again, changing to the same material might not be expensive at all. Like it might not even do anything
yeah, because that's quite bad for productivity I guess
You mean performance?
I guess it is quite expensive
yes
Not sure if accessing material multiple times is wise, you could use sharedMaterial
Modifying sharedMaterial will change the appearance of all objects using this material, and change material settings that are stored in the project too.
I wonder if it's nice to change all GameObjects that use this material, even though it can be used just by one simultaneously (in my case)
Quick question, what is the non-dumb way to do this? Or is there?
public float3 Rotate(float3 position, float3 pivot, quaterion rotation, int times)
{
float3 newPosition = float3.zero;
// I want to apply the rotation multiple times. I feel like you should be able to do something like rotation * times and get the same result. But, maybe I am wrong and just not thinking of it properly.
for (int i = 0; i <= times; i++)
{
float3 relativePosition = position - pivot;
float3 rotatedPosition = math.mul(rotation, relativePosition);
newPosition = pivot + rotatedPosition;
}
return newPosition;
}
That part talks about modifying the material, not replacing it completely
also might be bad for performance too, I guess ??
Well you dont have many options lol
yep, I just gonna use bool then
is float3 like Vector3 or what?
yeah, it's from the Unity Mathematics package. Used for burst optimisations
thanks, I see
by printing values, also when i invoke this block of code for 2nd time it prints right value since object instance is set
you're gonna need to show more code
if (ctrls.Player.Interact.triggered)
{
ItemToPickUp item = objectRaycasted.GetComponent<ItemToPickUp>();
item.SetInstance();
if (item.itemInstance is Resource newResource)
{
print(newResource.resourceQuantity);
}
if (playerInventory.GiveItem(item.itemInstance))
{
GameObject go = Instantiate(playerInventory.itemFeedPrefab, Vector3.zero, Quaternion.identity);
go.transform.parent = playerInventory.itemFeedPoint;
Destroy(go, 2);
go.GetComponent<itemFeed>().SetupFeed(item.itemInstance);
//DespawnItemServerRpc(item.GetComponent<NetworkObject>());
}
else
playerInventory.FullInventoryWarning();
}
this is class containing SetInstance() method
public class ItemToPickUp : NetworkBehaviour
{
public Item baseItem;
public Item itemInstance;
public bool SetInstance()
{
if (itemInstance == null)
{
itemInstance = Instantiate(baseItem);
}
askForItemServerRpc(this.NetworkObject);
return true;
}
[ServerRpc(RequireOwnership = false)]
public void askForItemServerRpc(NetworkObjectReference itemReference)
{
NetworkObject no = itemReference;
Item item = no.GetComponent<ItemToPickUp>().itemInstance;
if (item is Resource newResource)
{
askForResourceClientRpc(newResource.resourceQuantity);
}
}
[ClientRpc]
public void askForResourceClientRpc(int quantity)
{
if (itemInstance is Resource newResource)
{
newResource.resourceQuantity = quantity;
print(newResource.resourceQuantity + " should be equal " + quantity);
}
}
}
!code @mossy plover
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
The following table details the execution of ServerRpc and ClientRpc functions:
Its an RPC. It does not happen immediately even if its invoked on a local client
you'd just do an RPC back to the client and then do the rest of the logic
okay, thanks
which you already are doing?
^^ That.
But that can cause HUGE lag.
Like 100ms+ until you "pick up an item"
or something like that.
just fyi i'm pretty sure your server RPC is not going to work in a build or for other connected clients, as you are doing the object spawn in SetInstance and trying to send that to the server when only the server can spawn networked objects
At that point you would fix it by doing "client side prediction" and just assume that you player picked up the item locally and everything went ok.
already tested and its working, instance is local SO
yeah but how can i predict value of object?
or you mean something else
okay i figured it out, thank y'all for help
why do i need to make a parameterless constructor if i want to make different ones with parameters in inherited classes?
c# thing
You don't need one, as long as the child class calls a base constructor using the : base() syntax
public Child(int n) : base(n) { } - calls the base constructor that takes an int
Right, a parameterless constructor if you don't define one will default, but you still need to add base() I believe in c#
Correct
Quick weird question, would it be better to implement a saving and loading game system, at the start of a project or near the end or does it not really matter