#archived-code-general

1 messages · Page 114 of 1

dawn nebula
#

Truly beautiful.

lean sail
#

Is that for the gravity helper calculation?

#

On mobile so hard to go back to the scripts

hard estuary
#

Snake. 🐍

dawn nebula
#

This is the rigidbody positon of the projectile

lean sail
#

Ah nice

dawn nebula
#

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.

lean sail
#

awkwardsweat if they move there will be variation for sure

dawn nebula
#

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.

tidal dirge
#

why cant I add this prefab to the networkmanager network prefab list?

#

It doesnt show up and also doenst let me drag it in

fluid forge
#

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 ?

hard estuary
tidal dirge
#

Unity NGO

#

but I think I figured it out

#

its a canvas wich behaves different then a gameobject right?

hard estuary
hard estuary
# tidal dirge Unity NGO

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.

tidal dirge
#

only have one option tho

hard estuary
tidal dirge
#

1.4

#

omg nvm

#

im an idiot

hard estuary
# tidal dirge 1.4

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. 😐

tidal dirge
#

the answer was this

#

You dont add prefabs directly to the networkmanager anymore

#

it has a list where you have to add it

hard estuary
tidal dirge
#

ah ait

#

well that was dumb xD

digital fern
#

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
somber nacelle
#

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

digital fern
#

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

rotund burrow
#

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.

hard estuary
# digital fern How much scripts would you write to make a game character that have an inventory...

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.

digital fern
#

@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

heady iris
#

I've absolutely just learned that over time.

hard estuary
heady iris
#

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

hard estuary
digital fern
#

Alright then maybe i should :

  • Model : GenericCharacterData {skin,health,strength,defense,inventory,...}
  • Controller : GenericCharacterController {MoveTo(),Attack(),SwitchCurrentItem()}
  • View : GenerichCharacterUI{Refresh()}
digital fern
heady iris
digital fern
#

@heady iris So your characters are composed with abilities

#

Your architecture is looking like :

  • CharacterController
  • Ability1
  • Ability2
  • ...
heady iris
#

it's a pretty nice model

digital fern
#

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 🤣

hard estuary
# digital fern Alright then maybe i should : - Model : GenericCharacterData {skin,health,streng...

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.

digital fern
#

@hard estuary When you mention "Views" are you exclusively talking about UI ?

hard estuary
hard estuary
digital fern
#

So abilities are controllers ?

#

@hard estuary @heady iris What do you think about this

hard estuary
# digital fern So abilities are controllers ?

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.

digital fern
#

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

digital fern
#

So this kind of architecture is not completely junk

summer sable
#

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.
  1. 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.

rotund burrow
#

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?

fervent furnace
#

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?

rotund burrow
#

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

fervent furnace
#

you can just FindPath(Node[] nodes)
when pass your EnemyNode:Node, it will call the overrided method

rotund burrow
simple egret
#

child's link in parent but it will still call parent's methods
No, as long as it's correctly overriden (with override keyword) it will select the real type's methods

#

Otherwise class inheritance would be pointless and C# would not have it

fervent furnace
#

if you dont believe me, test it...
!code

tawny elkBOT
#
Posting 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.

rotund burrow
#

yes i tested it you're right

#

then i guess i can put EnemyNodes in neighbor list and it's not a problem

tidal dirge
#
    {
        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
tidal dirge
#

its not happening in general

#

the networking part is fine

clever mulch
tidal dirge
#

yes

#

is it possible to rotate a Rect transform?

heady iris
#

sure, they have a rotation

#

rect transforms are just Transforms with extra data attached, afaik

potent sleet
simple egret
heady iris
oblique basalt
#

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;
    }
potent sleet
#

should probably use a physics function for this though tbh

oblique basalt
#

isColliding is always true

potent sleet
oblique basalt
#

nothing as far as im aware

potent sleet
oblique basalt
#

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

karmic crown
#

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?

oblique basalt
#

thansk for the help

potent sleet
karmic crown
#

may take a while do you want me to send it in this chat here?

real ivy
#

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

fervent furnace
#

you want to reference a existing script in other object?

real ivy
#

yes

fervent furnace
#

public Drag drag
then assign it in inspector just like how you assign transform etc

fervent furnace
#

you can
by find desired object then get component

potent sleet
#

looks like objects are moving behind the camera or something

real ivy
potent sleet
#

does the z positioning move while this issue happens?

karmic crown
fervent furnace
#

idk how you will find the GameObject that have Drag component.....

real ivy
#

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

potent sleet
karmic crown
fervent furnace
#

if the hit.go have script that has Drag property:
hit.go.GetComponent<script name>.property name=this

potent sleet
swift falcon
#

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
},

swift falcon
#
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);
}
potent sleet
cursive ember
#

Hello, I would like to Invoke my onInteraction event but it isnt invoken... can anyone help me please?

karmic crown
potent sleet
swift falcon
#

all the data i need to save, a lot of stuff

potent sleet
#

thats obvious

#

but what data

#

if thats theproblem that should be ur first lead in

swift falcon
#

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

cursive ember
fervent furnace
#

idk unity event much
but i guess you need "IntDrive."onXXXXX

cursive ember
potent sleet
#

before if statement ig

fervent furnace
#

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

cursive ember
karmic crown
#

null thank you for your help I found the mistake ❤️

fervent furnace
#

so intdrive.oninXXX+=(this.)OnInteraction

potent sleet
fervent furnace
#

@cursive ember Try IntDrive.oninteraction+=OnInteraction

potent sleet
#

should be IntDrive.onInteraction += OnInteration

potent sleet
cursive ember
#

But i'm confused a lil

#

Why intDrive?

karmic crown
potent sleet
potent sleet
fervent furnace
#

you need a class reference see my previous explanation on above

maiden owl
#

How can I achieve this background effect in Unity?

scarlet talon
cursive ember
fervent furnace
#

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

maiden owl
#

Do I need to program the scrolling effect too, or is it an already existing feature?

proud trail
#

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

tawny elkBOT
#
Posting 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.

proud trail
#

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

maiden owl
# maiden owl

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?

scarlet talon
scarlet talon
#

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

maiden owl
#

Alright, thank you

#

I'm new to Unity so sorry for asking dumb questions, is this it or it's an unique 2D Material?

scarlet talon
#

That's it, you can change what type of shader it will use once it is created

maiden owl
#

I haven't touched anything regarding Shader yet though

#

Not sure even how to start messing with that

severe falcon
#

is there a better way to detect if a sword hits an enemy than OnTriggerEnter or does that method do just fine?

heady iris
#

that sounds very reasonable to me

scarlet talon
#

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

maiden owl
#

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

scarlet talon
#

If the color changed it means you are using a lit shader, see if you can find unlit

maiden owl
#

I am feeling dumb now

scarlet talon
#

Shader: Standard <--- change this to a 2d unlit type

maiden owl
#

Standard Unlit?

scarlet talon
#

That should work, but there is a 2d category too with its unlit version iirc

maiden owl
#

Thanks, that fixed the color issue

#

Now I need to figure out how to make it show in the screen

maiden owl
#

Jesus, configuring Unity is HARDER than programming on it

vagrant blade
#

@maiden owl Don't crosspost. This isn't a coding question, either.

maiden owl
#

Mb

scarlet talon
digital fern
#

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

maiden owl
# maiden owl

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

scarlet talon
#

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.

maiden owl
#

There's no size in the material's property

#

The wrap mode was already in repeat by the way

scarlet talon
#

You want sprites / default

fervent furnace
#

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

maiden owl
#

Alrighty, it's now at Sprites/Default

#

I still can't find a tiling size option

scarlet talon
#

Oh right, I had forgotten about that

fervent furnace
#

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

maiden owl
#

Even with repeat it doesn't keep repeating, probably because of the Tiling size thing

scarlet talon
#

@maiden owl You need to change draw mode in your sprite renderer to tiled

maiden owl
#

a.

scarlet talon
#

Then you can change the size in the sprite renderer itself

maiden owl
scarlet talon
# maiden owl

You can just do what that warning is telling you to

maiden owl
#

@scarlet talon I can't thank you enough for helping me 02hirohug

scarlet talon
#

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

maiden owl
maiden owl
scarlet talon
#

No such thing as dumb questions!

maiden owl
#
SpriteRenderer.material.mainTextureOffset = new Vector2(0, Time.time * ScrollSpeed);```
#

This is the code if you are wondering

scarlet talon
#

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.

maiden owl
#

I see

severe falcon
#

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);
        }
    }
}```
digital fern
cobalt gyro
dawn anchor
#

Hi i have install problem
It's been over 6 hours and it's the same way!

swift falcon
#

@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

dawn anchor
swift falcon
#

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

dawn anchor
swift falcon
#

What is the best/correct way to access prefabs in static methods?

vocal root
#

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?

swift falcon
# vocal root Hey, new with 3d attacks. Any1 know a good way to make the collider that deals d...

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:/...

▶ Play video
vocal root
#

unless i can track the transform of the bone

swift falcon
#

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

tidal dirge
#
    {
        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
vocal root
#

any way to check if a collider onTriggerEnter is a Box or a Sphere collider?

knotty sun
tidal dirge
#

the instantiated one right?

knotty sun
#

no

tidal dirge
#

its a prefab with a child object that has the component

latent latch
mossy snow
tidal dirge
#

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

mossy snow
#

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

tidal dirge
#

wait unity supports breakpoints?

#

damn

vocal root
#

Ive been trying different ways but this one doesnt even work xD

latent latch
#
collider is SphereCollider```
#

try that

vocal root
#

wow I didnt knew there was "is" for bools, cool. Ok this one works but I realized new problems hahaha, thanks!

latent latch
#

It's shorthand for what you're trying to do.

#

Pretty handy

vocal root
#

yup

hard tapir
#

Is this code legit?

#
            continue;```
leaden ice
#

Define "legit"

hard tapir
leaden ice
hard tapir
#

Like deal damage to all others col except its own

simple egret
#

You cannot collide with yourself

leaden ice
#

If you're using OverlapSphere or something it's reasonable

simple egret
#

Unless, you're using Overlap* methods

hard tapir
swift falcon
#

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 ❤️

harsh bobcat
#

quick check, x <<= 2 is equivalent to x *= 4 right

harsh bobcat
harsh bobcat
hollow loom
#

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

knotty sun
harsh bobcat
#

bit of a general question, how unwise is it to code in an unsafe context in unity?

knotty sun
#

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

harsh bobcat
#

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

knotty sun
#

but if they are arrays then they are in managed memory which can be moved unless you pin it

harsh bobcat
#

right

#

pointers is definitely a bad idea then

knotty sun
#

pointer into managed memory, very bad idea

harsh bobcat
#

wait im dumb

#

arrays are reference types

#

my bad

lean sail
#

Idk why u would need a pointer anyways

tidal dirge
#

I call GetComponentInChildren but it uses the component the parent what am I missing

lean sail
#

Use GetComponentsInChildren and skip the first element if u dont want the parent

knotty sun
lean sail
#

It really is an unfortunate naming convention though. I think everyone assumes what it does and is wrong at first

tidal dirge
#

oh it also includes the gameobject

#

dam

#

its a dumb name in my defendse but I get the usage

#

thnx

knotty sun
#

why anyone would use an api call for the first time and not read the documentation about it is beyond me

swift falcon
knotty sun
swift falcon
swift falcon
# knotty sun ```cs class MyClass : Monobehaviour public List<GameObject> gos; //fill in inspe...

I guess this was the idea I had at first.

  1. make a gameobject that is a singleton and just put in a lot of references in it to the prefabs
  2. 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.

lean sail
#

You could use an SO for the same thing without instanitating then

knotty sun
#

then use Resources.Load if that is what you want

swift falcon
lean sail
#

Use SO and SerializeField to drag in from the inspector

knotty sun
lean sail
#

I just meant to get away from singleton

swift falcon
knotty sun
#

The obvious answer is a static class, but you still need to find a way to populate it

lean sail
#

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

swift falcon
knotty sun
#
public static class MyStaticClass 
public static List<GameObject> gameObjects;

class MyClass : Monobehaviour
public List<GameObject> gos; //fill in inspector

void Awake() { MyStaticClass.gameObjects = gos; }
lean sail
#

Oh if it's just to access not to spawn then sorry yea static is fine

#

I guess spawning doesnt matter

swift falcon
#

I get the idea, sounds good. I guess the "way around" I have to do is exactly a way to populate the static class

lean sail
#

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

knotty sun
#

MyClass populates MyStaticClass and you populate MyClass in the inspector

swift falcon
granite nimbus
#

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?

lean sail
swift falcon
knotty sun
#

indeed, but why is that a problem?

simple egret
swift falcon
#

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

knotty sun
#

you just make sure MyClass has a very high execution order, i.e. runs before anything else

granite nimbus
simple egret
#

Like any other method implementing the "TryX" pattern

swift falcon
simple egret
#

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

knotty sun
granite nimbus
swift falcon
simple egret
granite nimbus
#

but does it comply with semver? it doesn't mention that

simple egret
#

Scroll up, I mentioned what format it accepts

granite nimbus
#

yeah and I also need to accept things like .pre-54

simple egret
#

From what I see from the semver spec, not all is accepted

#

Nah that doesn't accept that

#

Roll your own

granite nimbus
lean sail
# swift falcon sorry, couldn't understand what you meant by this, im dumb
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

swift falcon
#
  1. Thank you for the time and elaboration of your demonstration to help me ❤️
  2. 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
  3. 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'.
lean sail
#

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

swift falcon
#

wait, this doesn't work with static functions though..?

lean sail
#

SO can have functions

swift falcon
#

my mind if a bit of a mess tbh .-. I never used static functions a lot tbh

lean sail
#

Idk what the static function is for though

swift falcon
# lean sail Idk what the static function is for though

For example, in my case:

  1. 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.
  2. 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.
granite nimbus
#

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)

granite nimbus
#

although they don't mention it as C# compatible (I dunno if it matters at all)

lean sail
#

U can use regex in c#...

potent sleet
#

regex is regex

#

there is no c# or non-c# version

granite nimbus
lean sail
granite nimbus
#

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

potent sleet
#

it's like a universal thing

granite nimbus
#

okay 🙂

swift falcon
# lean sail Ah, you will need something else that declares when it should drop. Since the SO...

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

lean sail
#

you can still make that static, but something is going to have to call that function

granite nimbus
#

thing that bothered me is that they specifically listed some languages, so I thought maybe it's dependent on language, but thanks for clarification

potent sleet
#

like how different dialects of the same language

simple egret
# granite nimbus okay 🙂

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

potent sleet
granite nimbus
swift falcon
simple egret
lean sail
#

i love that site

simple egret
#

If you have some test cases, it even supports that!

lean sail
granite nimbus
#

okay it says error for one of them, so yeah it helps, I use the second one

#

thanks a lot

swift falcon
#

basically make this @lean sail

lean sail
granite nimbus
#

weirdly it says no match with "1.1.1"...

lean sail
#

does for me

#

dont put commas if u did

granite nimbus
lean sail
swift falcon
#

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

lean sail
#

well idk how u populated that but it should work

lean sail
swift falcon
#

BUT @lean sail , fortunately I have the perfect workaround

#

OdinInspector: odin static inspector ❤️ ❤️ ❤️

#

OdinInspector: odin static inspector ❤️ ❤️ ❤️

granite nimbus
#

probably newline character

lean sail
#

ah yea u can see the newline in your regex image

#

its the little down left arrow

granite nimbus
#

yeah I see, thanks

#

it works now

lean sail
#

yea that regex really doesnt have anything too complicated, i wouldve been very surprised if it didnt work in .net

granite nimbus
#

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

lean sail
#

i believe it uses a state machine, been years since ive actually looked into it though

swift falcon
#

@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

vocal root
#

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

kind wolf
#

can someone help why cant I pass nulls in the function?

swift falcon
#

@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

vocal root
#

tags are correct, its one of the first things i checked over and changed to try other things

lean sail
lean sail
kind wolf
#

lol

#

this is the error i get

lean sail
#

make the parameter nullable, it should work

#

Item? i

swift falcon
kind wolf
#

yea scriptable object

swift falcon
# kind wolf what debugger?

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

kind wolf
#

is this what you meant? ima be honest ive never seen this before lol

lean sail
#

uh if its not needed with unity objects then u wont need that

kind wolf
#

only jetbrains

lean sail
swift falcon
#

where are you writting your code?

kind wolf
swift falcon
#

Visual Studio?
VS Code?

kind wolf
#

yea

#

vs code

lean sail
#

is slots itself null, is slots[index] null, or is slots[index].item null

swift falcon
#

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...

▶ Play video
lean sail
#

theres a big difference

kind wolf
lean sail
#

well u cropped to only show a screenshot of 1 line..

kind wolf
#

yea sorry

lean sail
#

also just paste it with !code blocks

tawny elkBOT
#
Posting 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.

lean sail
#

its small enough

kind wolf
#

ah alr

#

this is stupid tho cuz id have to make a shotty work around instead of having a nice clean function

kind wolf
kind wolf
#

hm good question let me check

#

oh wait

#

yea i think thats it

lean sail
#

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

kind wolf
#

oooooooh

#

i was running update hotbar after setting the player

lean sail
#

🧠 i am my own debugger

kind wolf
#

i mean

#

before setting the player*

#

lol thanks I wouldve been stuck on this for so long

lean sail
#

np

vocal root
#

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

simple egret
dark shell
#

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

pulsar dove
dark shell
lean sail
#

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?

dark shell
# lean sail What you're describing is kinda vague, but i dont really see how this would be a...

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

lean sail
pulsar dove
lean sail
#

They're also going to be very fragile

dark shell
lean sail
#

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

dark shell
# pulsar dove While its a rudimentary solution, I would draw out your state machine ideas firs...

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

lean sail
#

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

cobalt gyro
#

Does anyone know how to turn a double into a float

lean sail
tidal shadow
dusk apex
lean sail
#

you can get random floats with unity

dusk apex
cobalt gyro
dusk apex
radiant trout
#

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

dusk apex
radiant trout
dusk apex
radiant trout
#

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

dusk apex
cobalt gyro
dusk apex
cosmic rain
#

Documentation 🪄

lean sail
#

classic XY problem as well, ask how to get a random float rather than asking how to convert a double to float

mild coyote
#

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

hexed pecan
#

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?

potent sleet
#

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

hexed pecan
#

Its easy from one position. Along a line is trickier

lean sail
#

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

hexed pecan
#

With mesh colliders you could also potentially utilize the mesh data (and hit.triangleIndex) directly

lean sail
#

i too am curious though of the use case, this seems extremely niche

mild coyote
hexed pecan
#

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

mild coyote
severe falcon
#

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?

fervent furnace
#

check if the HealthComponent on other.gameObject is null

hexed pecan
#

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

severe falcon
#

there is also a collider on the child so ill use other.GetComponentInParent. thx for the help

misty zinc
#

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.

cosmic rain
#

Aside from that, yes, it's possible.

hexed pecan
#

Yeah, you probably want the Renderer component and then access its materials

deep lantern
#

Hi all. How to AddListener a method to an event on Awake() or Start() but it require some parameter?

misty zinc
deep lantern
hexed pecan
#

You said

take a specific kind of component
That component would inherit from Renderer

misty zinc
hexed pecan
#

All renderers have materials

hexed pecan
misty zinc
hexed pecan
#

I'm still not 100% sure what you are doing. Is it like an editor helper script?

deep lantern
hexed pecan
#

@deep lantern Look into System.Action for delegates that can take parameters

misty zinc
deep lantern
misty zinc
#

I'd do post processing, but that doesn't work for objects that move independently to the ground.

hexed pecan
misty zinc
#

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.

hexed pecan
#

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

cosmic rain
#

Changing the material property should work. Might not be as optimized as a custom shader though.

misty zinc
#

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):

fervent furnace
#

the wavelength is increased/decrease but the factor is 1/c...

misty zinc
#

I know. I just had to figure out how to link the math to actual results on the screen.

fervent furnace
#

maybe you need to multiply the delta change to emphasize it effect..

misty zinc
#

Haha no! I'm gonna lower the speed of light

grim smelt
#

how should i get the GameObject that my Physics.RayCast hits?

prime sinew
#

It'll tell you

grim smelt
#

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);

granite nimbus
#

started learning regex syntax 🤣

grim smelt
#

RaycastHit doesnt have a .gameObject property or anything

#

just a .collider and .rigidbody

prime sinew
#

i dont know what version of Raycast you're using

#

but there's one with a RaycastHit out variable

granite nimbus
grim smelt
#

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

granite nimbus
grim smelt
#

but my IDE is telling me that's always false?

grim smelt
prime sinew
granite nimbus
#

yeah show code

#

it's weird for IDE to show it's always false

#

cause it's from out variable

grim smelt
#

do you want the whole file

#

or just that part

granite nimbus
#

just where you do physics.raycast

grim smelt
#
            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);
prime sinew
#

use ==

grim smelt
#

im used to using is for comparing to null/constant values in normal c#

prime sinew
#

there's something about how Unity objects are null checked differently

grim smelt
#

i heard somewhere that it's faster or something?
or works better than .Equals() for strings or something? cant remember

granite nimbus
prime sinew
#

== null is the safest

granite nimbus
#

use ==

grim smelt
#

ah ok

granite nimbus
#

that's because Unity overrides == for gameobjects

#

but not is

grim smelt
#

ah

granite nimbus
grim smelt
#

can i make the GameObject nullable

#

GameObject? @object = hit.rigidbody.gameObject; like this

lean sail
#

That wont help anything

granite nimbus
lean sail
#

Even if it did work

granite nimbus
#

by virtue of being an instance of a class

grim smelt
#

huh, weird.

lean sail
#

The functions that take the game object wont like it, and itll break

grim smelt
#

how come im still getting NREs then?```cs
GameObject @object = hit.rigidbody.gameObject;
Debug.Log(@object == null ? "null" : @object.name);

prime sinew
#

why dont you check it inside the if statement

lean sail
#

You are trying to get the game object of something that is null, then checking if that object is null

prime sinew
#

your Raycast returns true if it did hit something

grim smelt
#

oh

#

i thought gameObject would be null lol

grim smelt
#

but the if statement only gets run if the ray is hitting something

granite nimbus
#

also are you sure you want to use .rigidbody and not .collider?

grim smelt
prime sinew
# grim smelt ?

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;
}
granite nimbus
#

the difference is that nobody guarantees it has a rigidbody

prime sinew
#

yes and only if it hits something then hit wont be null?

grim smelt
prime sinew
#

never mind. maybe i'm not understanding the issue

grim smelt
#

i guess in my case all my colliders have a rigidbody so i didnt notice anything

#

good call tho

granite nimbus
grim smelt
#

although i think its just easier to surround my code in a try/catch

#

for my scenario

#

thanks tho

prime sinew
#

and in the future please dont crosspost

grim smelt
prime sinew
#

you pick one

grim smelt
granite nimbus
prime sinew
#

ye

granite nimbus
#

keep in mind that any exception you throw in built game = crash = mad email to you that game doesn't work

grim smelt
#

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

lean sail
#

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.

granite nimbus
#

so yes

lean sail
#

You could try catch your entire game, but theres very good reason that no one does

grim smelt
#

ah ok

grim smelt
hexed pecan
#

Aren't exceptions really bad for performance?

lean sail
#

Try catch is for when the errors are out of your control. Like searching for a file and the player deleted it

hexed pecan
#

Is it just when you throw the exception or does just having try/catch itself introduce large overhead too?

granite nimbus
#

@grim smelt in general - exceptions are not meant to be used for something that you know will happen

lean sail
#

Try catch itself wont be any noticeable performance hit

granite nimbus
#

exception is something like you didn't get right format of data from an external database

#

something you have 0 control over

grim smelt
#

oh ok

lean sail
summer sable
#

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.

cosmic rain
fervent furnace
#

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

gray mural
#

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?

prime sinew
hexed pecan
#

Is the object at 0 rotation before you do that?

#

Ok I assume it is 2D

gray mural
gray mural
gray mural
main token
#

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?

prime sinew
main token
#

I tried both assigning through serialized properties and doing it through GameObject.FindWithTag()

#

somehow it's null either way

prime sinew
#

but they are still in the scene?

#

and are these references on a DDOL?

lone cape
#

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

main token
lone cape
#

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

twin hull
#

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...

lone cape
#

exactly

#

yes spot on

twin hull
#

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

lone cape
#

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

twin hull
#

"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?

lone cape
#

yes

#

well the minions are telling a function in Ability to listen

twin hull
#

then it'll be the same function called twice

lone cape
#

So the ability needs to be unique?

twin hull
#

but i'm assuming each ability function is an instance because otherwise myCardComponent would be the same

lone cape
#

the minion is its own instance but idk if the abilities needed to be aswell

twin hull
#

where are you getting myCardComponent then

lone cape
#

ill try making the ability unique before i add the listener

lone cape
twin hull
#

but if ability isn't a unique instance then it just overwrites it

lone cape
#

maybe thats whats happening

plush sparrow
#

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

lone cape
#

Works now Thanks @twin hull

twin hull
#

😭

lone cape
#

😆 I didnt think abilities needed to be unique if the Minion itself was

cosmic rain
plush sparrow
#

building then sharing via whatsapp or dirve

cosmic rain
#

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.

fresh cosmos
#

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?

knotty iron
#

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?

cosmic rain
hexed pecan
#

Messing with textures on the CPU side is pretty slow but if that's not a problem then use that

fresh cosmos
hexed pecan
#

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

fresh cosmos
#

yeah, i think that would be the simplest way to get something working to se if its worth expanding on

fresh cosmos
#

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

fresh cosmos
#

ive instead resorted to setting up a scene to render screenshots to make textures of the different icons i need

elder temple
#

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

ashen yoke
#

but the cleanest way is to use MaterialPropertyBlock

stoic ledge
#

has anyone used NavMesh navigation in 2D?

cursive gorge
#

Does OnDestroy event run when we do application.quit?

native fable
#

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?

unborn flame
#

what does this mean and how can i fix it?

knotty sun
unborn flame
knotty sun
#

no

proud trail
tawny elkBOT
#
Posting 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.

knotty sun
#

that looks like the entry in a try catch block

proud trail
#

use this so people can see the full code other than a single png, jpeg, ect.

hexed pecan
#

If you look a bit lower on the Stack trace it should show you the real source of the error

#

Not the exception

proud trail
#

can help to come up with more solutions

unborn flame
#

tbh i have no idea what any of that means

severe geode
#

i just function print error bro
you should ask who owner of asset, ask theme

hexed pecan
#

It has links to the code that caused the error, in the order it was called (from bottom to top)

knotty sun
#

it's a call stack, not a lot of help in a try catch block

knotty sun
unborn flame
#

that isnt my code

#

its the error

knotty sun
#

you posted a single line of code. The line starting 'throw'
you need to post the complete try catch block

hexed pecan
knotty sun
#

yes, because a catch will not show the origin of the exception

hexed pecan
#

Is trace more for when it has crashed

hexed pecan
knotty sun
#

we can only know that it has occured within the try catch block

hexed pecan
#

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

knotty sun
#

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

proud trail
#

!code

tawny elkBOT
#
Posting 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.

vocal root
#

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;
                    }
wispy wolf
#

@vocal root are you doing this in every Update?

vocal root
#

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

wispy wolf
#

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.

vocal root
dim umbra
#

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?

wispy wolf
#

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.

vocal root
#

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?

tawny mountain
#

How can I make a sprite that's small easier to click and drag?

potent sleet
tawny mountain
# potent sleet 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

radiant marten
#

so regardless of what I click on: the shadow, camera, or arrow object--it will always select the Player object

tawny mountain
radiant marten
#

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

tawny mountain
radiant marten
#
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

tawny mountain
#

yeah I couldn't get a parent object to drag

#

added the script , collider , rigidbody 2d and nothing happened

radiant marten
#

you may have to do your own gizmo coding

tawny mountain
#

oh dang I don't know anything about that

radiant marten
#

but again, this only works if the object is selected...

tawny mountain
#

I should add a selected highlighter

#

To highlight the object mouse gives over

dim umbra
tawny mountain
#

Share a screenshot. But its probably tearing ( lines appear where the tiles touch )

dim umbra
#

i assumed it would embed, but yea that's probably it

#

how do I fix that

grim smelt
#

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?

fervent furnace
#

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

fast aurora
#

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..?

tawny mountain
radiant marten
fast aurora
severe geode
fast aurora
#

I mean my whole code structure is completely different than what the guy is doing, since it's quite inefficient

severe geode
fast aurora
#

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

severe geode
#

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

fast aurora
#

what is that website even

gray mural
#

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

severe geode
#

you just make feature check if already material for place type

#

and dont change material it if that obj is already has material type

gray mural
severe geode
#

or tutorial on youtube

gray mural
#

maybe I should consider using WaitUntil?

severe geode
#

is have many and right way to design code

gray mural
gray mural
#

I am just changing its material

severe geode
#

are u newbie code?

gray mural
severe geode
#

if yes you should try learn it link
is have code, design pattern how to change material for right way, optimize

gray mural
#

so making a border

hexed pecan
hexed pecan
#

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

gray mural
hexed pecan
#

You mean performance?

gray mural
hexed pecan
#

Not sure if accessing material multiple times is wise, you could use sharedMaterial

gray mural
mild orbit
#

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;
}
hexed pecan
gray mural
hexed pecan
#

Well you dont have many options lol

gray mural
gray mural
lucid valley
mossy plover
#

anyone knows why in my code print is done first?

lucid valley
#

how have you tested that the print is done first?

#

As i can reasonably bet it wasnt

mossy plover
#

by printing values, also when i invoke this block of code for 2nd time it prints right value since object instance is set

lucid valley
#

you're gonna need to show more code

mossy plover
#
                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);
        }
    }
}
potent sleet
#

!code @mossy plover

tawny elkBOT
#
Posting 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.

fleet furnace
#

Its an RPC. It does not happen immediately even if its invoked on a local client

mossy plover
#

oh okay

#

is there way to avoid it?

#

like some sort of semaphore

lucid valley
#

you'd just do an RPC back to the client and then do the rest of the logic

mossy plover
#

okay, thanks

lucid valley
#

which you already are doing?

fleet furnace
#

^^ That.
But that can cause HUGE lag.
Like 100ms+ until you "pick up an item"
or something like that.

lucid valley
#

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

fleet furnace
#

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.

mossy plover
mossy plover
#

or you mean something else

#

okay i figured it out, thank y'all for help

rotund burrow
#

why do i need to make a parameterless constructor if i want to make different ones with parameters in inherited classes?

latent latch
#

c# thing

simple egret
#

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

latent latch
#

Right, a parameterless constructor if you don't define one will default, but you still need to add base() I believe in c#

rotund burrow
#

so it needs to call any parent constructor first

#

or it doesnt work

simple egret
#

Correct

halcyon steeple
#

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

latent latch
#

I'd get an idea how the save system works before you start implementing assets with a lot of nested data

#

and the general scope of what you want to save