#archived-code-general

1 messages ยท Page 332 of 1

naive summit
#

My bad, accidently put an . there

somber nacelle
#

yes

naive summit
#

Thank you :))

exotic reef
#

raycasting wont work , as some portoin of cuboid can possible still go inside terrain , bcz it only ensures hit.point be above terrain not the whole cuboid , and about boxcast i dont know what that is , i will see how to use it, thxx

somber nacelle
#

i guess you don't know about the existence of math to determine where in relation to that hit.point you would put the object?

exotic reef
somber nacelle
#

yes

exotic reef
#

but that wont work , bcz only the transform.position = hit.point , not ensuring if the whole bounds of cuboid are above terrain , bcz terrain is not flat

somber nacelle
#

again, do you not know that math exists? you know you can use the bounds of the collider to determine how far you need to offset the position from the hit point, right?

dusk apex
exotic reef
#

is it something like , the bounds of overlapping collider - hit.point for X and Z axis?

fossil temple
#

yo someone tryna help me

#

๐Ÿ˜Š

somber nacelle
fossil temple
somber nacelle
somber nacelle
# fossil temple

yes, you can ask for help in here like literally everyone else

fossil temple
somber nacelle
#

the thing is though, is that you have to ask a question if you want help

somber nacelle
fossil temple
#

ip grabber

#

phisher

#

stay away pal..

#

ight na seriously tho @somber nacelle U tryna help me with sum

somber nacelle
#

it's not even my website, genius. and it is a permitted link

fossil temple
#

why :/

#

:(

somber nacelle
#

you haven't even bothered asking a fucking question

fossil temple
#

ight my bad

dusk apex
#

Basically instead of asking if someone's available to help, just ask your question. If someone who is on the server feels like they want to answer/help you, they will.

fossil temple
#

how do i make my player die after contact with object

dusk apex
#

Break the problem down.
Define contact. Define die.

fossil temple
#

ight so

somber nacelle
#

or just like google the question

dusk apex
#

For example: On collision enter and Destroy

fossil temple
#

when red touches white

#

i want white to

#

die

#

and game over screen happens

#

also sub question: do i make game over screen first then add the contact on death thing

dusk apex
#

Without knowing anything about your setup (physics or no physics), there isn't much that folks can suggest without fishing for more information or simply designing your game.

fossil temple
#

what more information do i provide

dusk apex
#

Are you using physics?

#

How are you evaluating contact?

fossil temple
#

im ngl what is physics

#

ohh

#

i searched

#

ye i am

#

and i am evaluating contact by when on screen red touches white

dusk apex
fossil temple
#

since I want to make it so that when red comes in contact with white a game over screen shows up and users get option to restart or exit, do i make the game over screen first

dusk apex
#

Your eyes can perceive it but how is your application going to be evaluating contact?

fossil temple
dusk apex
#

So.. with rigid body physics, character controller, collider cast, other physics casts or ?

fossil temple
#

rigid body

dusk apex
#

Google Unity Rigidbody collision
There ought to be plenty of tutorials on this. After acquiring this feature, determine how or what you'd define as "die".

fossil temple
#

bro i aint gon lie

#

u the most useless person i met in my entire life

#

i deadass just had a conversation w a brick wall

lean sail
fossil temple
lean sail
#

Yes, many beginners do.

night storm
#

surely if u googled u would have found something..

fossil temple
#

nah not anything that works

lusty zephyr
# fossil temple ip grabber

๐Ÿ˜€ idk if you know a lot about tech, but IP grabbing is basicly useless. The only thing what's dangerous about it is that they know your location.

spring creek
lusty zephyr
#

I'm not living under a rock

spring creek
gray mural
# fossil temple pls stop talking to me

It's so that the people, posting here, are usually expected to already have some intermediate knowledge about coding. If you don't, consider posting in #๐Ÿ’ปโ”ƒcode-beginner. There, you're expected to at least be able to use any suitable browser to find the information you're supposed to know. If this is beyond your skills, consider not asking at all.

blissful vector
#

One thing is when jm moving from top of ladder to bottom its not going on the launder(ladder is slanted so i want it to roll it over it). Its kinda launching itself and landjng luckily

#

Also the turn its making from red platform to ladder is instant, I want it to be seemless

green wharf
#

i have a tps character and im using a state machine, should i create a state for my character's aim state or should i check if im aiming in other states (if anyone can help i can send you the project, because something feels wrong)

#

the character's movement system changes while aiming

naive summit
#

Hi, im working on a door raycast script and im pretty new to this raycast stuff so i may not understand completly but logically why isnt this working.

public class DoorRaycast : MonoBehaviour
{
    MyDoorController mydoorcontroller;

    public void Awake()
    {
       mydoorcontroller = gameObject.GetComponent<MyDoorController>();
    }

    public void Update()
    {
        if(Input.GetKeyDown(KeyCode.E)) 
        {
            RaycastEvent();
        }

    }

    public void RaycastEvent() 
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.forward, out hit, 100f))
        {
            mydoorcontroller = hit.collider.gameObject.GetComponent<MyDoorController>();
            if (mydoorcontroller != null) 
            {
                mydoorcontroller.PlayAnimation();
            }
            else 
            {
                Debug.Log("NotFound!");
            }
        }
    }


}

When e is clicked it sends an raycast and if the object that was raycasted has MyDoorController script then the PlayAnimation() Inside it is called, or Debug.Log is called. However when i click E on the door nothing shows up in the console at all

dusk apex
#

Place a log and see if the method was called

knotty sun
#

to start with add a debug if the raycast fails

naive summit
knotty sun
#

well it wont if the raycast fails

dusk apex
naive summit
#

I think i found the faulty one.

public void Update()
{
    if(Input.GetKeyDown(KeyCode.E)) 
    {
        RaycastEvent();
        Debug.Log("E was clicked!");
    }

}

It never debugs anything in the console

#

Bug the code looks correct so why is that

knotty sun
#

the object or sript is disabled

dusk apex
#

Is the object inactive? Is the component disabled? Did you save?

#

Are logs enabled in the console window?

#

Have you tried turning Unity off and on again?

naive summit
#

Alrighties i fixed the E problem, so now E is debugged, Raycast gets sent out successfully but the other script is not found

#

I have a GameObject called DoorPivot, and inside it a GameObject called Door. Now the DoorPivot has the script but it doesnt have a box collider, while the Door itself has the Box Collider but not the script, could that be whats causing this?

#

Since i thought because that Door is a child of DoorPivot it automaticly is detected too

spring creek
dusk apex
naive summit
exotic reef
# lusty zephyr ๐Ÿ˜€ idk if you know a lot about tech, but IP grabbing is basicly useless. The onl...

there is a reason why windows and Browser bring updates every now and then , Grabbing IP is a stepping stone for an attack , I use Google Chrome , and it has some network vulnerabilities now also , I got a browser hijacker with a keylogger too , by just opening a fishy redirected ad link , not even downloaded anything .
I talked to 3-4 more people who opened that website , they got it too . The best guess is , the hackers have used my IP adress to connect to my network and find network vulnerabilities in chrome , and installed a malicious plugin in chrome and other browsers , after that my browser had this " Managed by your Organisation" , with 2 russian malware pugins installed in my edge browser .
So never underestimate hackers and always use an adblocker .
Although rare , but u can be a victim of an exploited vulnerability of a browser ( altho they are patched quickly in most cases)

lusty zephyr
exotic reef
lusty zephyr
exotic reef
spring creek
exotic reef
exotic reef
spring creek
lusty zephyr
#

It's like your local address. if we have it, then we can't teleport to you

dusk apex
# exotic reef what do you mean ? i didnt understood?

Even if you had the IP address of some random individual, you'll likely not be able to exploit them unless you're aware of some application that they're using and if you're given consent to launch the application without constraint.

exotic reef
spring creek
static matrix
#

do static attributes persist between scenes, assuming they aren't tied to an object

dusk apex
knotty sun
dusk apex
#

More than likely though, you've contracted a virus or malware through installing some component/app or have given permission you weren't aware you were giving.

static matrix
#

public static int, so on and so forth

rigid island
#

ohh a field, yeah as SteveSmith mentioned they will

simple egret
#

(these cannot be marked as static)

exotic reef
# spring creek No offense, but you have a profound misunderstanding about what an IP address is...

I am certainly not a cyber security expert , but i know that grabbing IP address is the first step to any cyber attack , it can tell a hacker which system to attack ,
I have experienced it myself so i believe it in it , and i have read some blogs from Microsft , nordVPN and This forbes blog also i am attaching , i am not trying to convince u or so , but i believe in this, bcz i suffered a whole day bcz of it and always now use an adblocker

spring creek
static matrix
#

if I assign a field to a prefab (like the value is a script attached to a prefab) can I change that? like is it an instance I can alter

latent latch
#

discord has your ip address

#

watch out

static matrix
#

every website does

#

thats how websites work

exotic reef
static matrix
#

unless you use a vpn

#

is this in any way related to unity btw?

dusk apex
spring creek
static matrix
#

ah whatever
ill figure it out

exotic reef
lean sail
night moss
#

If I have two empty gameobjects in the same position acting as "connecters" how could i find other connecters starting from a connecter? Hope I made myself clear

knotty sun
spring creek
rigid island
lean sail
#

Cant use physics if they're empty

vagrant blade
#

Can we move on from this IP thing, it's not even Unity related

static matrix
night moss
dusk apex
rigid island
#

keep stored stats in a POCO

fleet tide
#

Sorry, can you explain me more ? I'm not sure to understand completly

dusk brook
#
var x = GameObject.Find("Hidden Layer Node 2/Input value");
Debug.Log(x);
var y = x.GetComponent<Text>();
Debug.Log(y);

Somehow y is null here?
x is logged as Input value (UnityEngine.GameObject) so I'm not sure what's going wrong here

#

I just want to grab the text elment

dusk apex
#

Was there an error?

dusk brook
#

This is the input value so it is a text element... Is the Text class referring to the legacy Text element?

dusk brook
fervent furnace
#

dont use find/get component if possible ie you can reference it
use TMP_Text

dusk apex
#

That likely means x isn't what you think it is or that it really doesn't have said component

rigid island
#

Text is def not TMP_Text

#

also no reason this should be a find. As @fervent furnace mentioned use a serialized field

dusk brook
dusk brook
#

What is the time complexity of Find?

#

Should I store all the objects or is it fine to keep re-calling

rigid island
#

its extremely slow and makes decent amout of garbage, thats all i know

fervent furnace
#

O(number of gameobjects in hierarchy)

dusk brook
#

๐Ÿ‘ Cheers guys

rigid island
#

oh god this site

#

Debug.DrawRay maybe ?

somber nacelle
#

if you're on 2022+ use the physics debugger

#

if you are on a version older than that, you'll need to draw the raycast with debug.drawray or something

rigid island
green wharf
#

im using unity editor 2022.8.3f1 but cinemachine 3 is not available

rigid island
#

2022.8 ?

green wharf
#

2022.3.8f1

#

my bad

rigid island
green wharf
#

i did

somber nacelle
# green wharf 2022.3.8f1

pretty sure you can manually install it by name in that version. but is there a particular reason you are using such an old patch of 2022.3?

green wharf
rigid island
#

hmm maybe you could manually change manifest

green wharf
#

which is the best version other than unity 6?

somber nacelle
#

then just update to the latest patch if you don't have any real need to be on that specific patch version

green wharf
#

ok thanks

somber nacelle
#

the latest 2022.3 version is 2022.3.31. you are currently on a patch that came out in august of last year, which is also before cinemachine 3 was actually released from beta

rigid island
#

please use a better site for code !code

tawny elkBOT
rigid island
#

this site is junk

#

ty

somber nacelle
#

have you actually enabled the physics queries in the physics debugger?

rigid island
#

it looks like this for me ๐Ÿ˜ฆ

#

nothing is changed in the code, if you're using physics queries the code is not important to draw debug them

#

this video will show you how you can see them in the playmode with built in analyzer
(window -> analysis -> physics debugger)

somber nacelle
#

if you do not see any raycast after enabling the queries in the physics debugger then you need to check your conditions to make sure that they are actually allowing the raycast to be fired

rigid island
#

can you show it where you enabled

#

but yeah now im starting to lean towards your code being sus

#

if (isShot == true && ammoClipLeft > 0 && isReloading == false)

#

ook good. Just double checking

#

maybe throw some debug.logs in there and see if that section is even being hit

somber nacelle
#

do you see anything if you also enable Cast there?

rigid island
#

which part of the shooting?

#

Ohh

#

you know what you need that

#

thats your raycast

#

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

somber nacelle
#

what do you mean by that

rigid island
#

the ray is working

somber nacelle
#

so you do see it then?

rigid island
#

don't

#

I think you're assuming its supposed to come out of the gun

#

if you want ray to come out of the gun, you need to set the ray start and direction from your shooting point

#

just an empty gameobject

#

call it (firePoint) or some shit

#

ideally its child of the gun and if its child of camera, they should have correct look direction

#

make sure (blue) arrow points forward in local mode (not global)

#

then you can just do
ray = new Ray(firePoint.position, firePoint.forward)

heady iris
#

it's very common to use empty game objects as reference points

#

game objects don't have to have any components on them (other than the Transform)

#

that's not jank at all

gray mural
# fleet tide Sorry, can you explain me more ? I'm not sure to understand completly

I'm saying I would consider creating a specific class, which might store the essential data for the merged ScriptableObjects. This class can also have a static method, which takes a List of the ScriptableObject as its parameter, and updates the necessary variables

public class Spell
{
    public Spell(...) { ... }

    public static Spell Merge(List<SteamoxSO> steamoxSOs) => new(...);
}

//
public List<Spell> spells = new();

//
spells.Add(Spell.Merge(selectedItems));
rigid island
#

whats jank about it ? its pretty common

#

do note it also depends on the game, some games the ray does not come out of the gun just the visual FX

#

Counter-Strike is a good example of this

#

(the weapon ray always fire from center of screen)

heady iris
#

I need a heap with a decrease-key operation. Any suggestions for a library?

#

I'm looking at implementing a Fibonacci heap, and it's mildly scary looking

#

certainly compared to a binary heap

#

C#'s PriorityQueue does not have a decrease-key operation (and it's not available anyway)

#

I might just insert duplicates. This is for A*.

heady iris
#

so in A*, you might discover a cheaper path to a node that you haven't visited yet

#

you store all of the unvisited nodes in a heap

#

you can either push a duplicate element with a lower value or decrease the value of the item already in the heap

#

I'm...not using a heap at all right now, so maybe I should do that first ๐Ÿ˜…

leaden ice
#

Would a SortedList be good enough

#

Just remove and re-add an element when you find a cheaper cost

heady iris
#

adding items into a SortedList is O(n), which can be pretty punishing if you're adding and removing items at roughly the same rate

#

heap insertion (and removal) are both logn

leaden ice
#

Sorted dictionary?

heady iris
#

(and fibonacci heaps apparently get amortized O(1) for insertion too, scary)

#

a SortedDictionary is a binary search tree, which is also worse than a heap for this purpose

#

I completely forgot I wasn't actually using a heap yet, so I'm going to do that first lol

viscid stump
#

hey guys can i have some help? for some reason im putting a text on my screen in unity and its not showing up in game view

#

also in scene view its all blury so im not sure if im doing something wrong?

#

im a beginner by the way

heady iris
#

this is not a code problem

viscid stump
#

hm , can i show you a picture of show my screen over a muted call perhaps?

fleet tide
viscid stump
gray raft
#

what will be the best method to make these lazers?

rigid island
#

Line Renderer maybe ?

#

they seem pretty simple

#

I used a similar approach drawing with a Raycast, you just need a good material

fleet tide
night moss
#

With that I solved a problem i was trying to fix for 3 days

lean sail
night moss
quaint crypt
#

how do I rotate a rect transform around it's center? regardless of where the pivot / anchors are. I've tried iconRT.RotateAround(iconRT.TransformPoint(iconRT.rect.center), Vector3.forward, (rotated) ? 90 : 0); but it still rotates around the top left corner of the RT and not the middle.

edit: nvm im stupid

vapid harbor
#

Is it possible to fork unity and contribute to it/modify?

somber nacelle
#

the engine itself is closed source, except for the c# bindings. there are open source packages though. i'm not sure if they accept contributions though

heady iris
#

at least, packages whose source you can look at; they aren't FOSS-licensed

hollow dust
#

does anyone know any good melee combat tutorials? for punching?

chrome trail
#

So, as you can see from the GIF, I have a problem where the mesh renderer appears to be very selective when rendering the areas that have been dug out. What I've been able to deduce so far is that this is caused by the fact that, rather than the ground being a single 10x10 mesh it's 10 1x1 meshes linked together. However, I don't want to fix this by making a single 10x10 mesh since it's not going to scale well with the project. So how do I solve this problem without doing that?

rancid frost
#

is it normal for memory to not be released in editor?
ive destroyed game objects containing mesh data, but yet the amount of memory that belongs to mesh according to profiler does not decrease

#

Nothing is being shown but yet 1.8gb in meshes?

cosmic rain
#

To clarify point 2, assets are not unloaded or destroyed by the GC as objects do(when all references to it are lost).

#

And mesh data is considered an asset.

rancid frost
#

I see

#

I know GC would not be called on some unity objects, so i ttried clearing out mesh before deleting, but even that did nothing

#

Strangely enough, it seems the editor frees the memory if you need more

cosmic rain
#

And is that during play mode?

rancid frost
#

negative, im in editor

cosmic rain
rancid frost
#

copy

#

let me see

#

sec, let me restart scene and test

#

picture 1) Empty scene
pci 2) scene after work
pic 3) scene after clear.

#

didnt work

cosmic rain
#

There's also a possibility of you having a leak. If you generate several meshes during the session and reassign them where previous meshes were assigned without destroying the old ones.

upbeat furnace
#

hey so I am making a wave type system however for some reason when the next wave comes it refers to the previous wave sorta like this:
Wave 1 > Wave 1 > Wave 2

{
     //Calculates the number of enemies in a wave to spawn (this is set in the Wave scriptable object)
     for (int waveNumber = 0; waveNumber < currentWave.NumberToSpawn;)
     {
        int enemytoSpawn = Random.Range(0, currentWave.EnemiesInWave.Length);
        int enemySpawnPoint = Random.Range(0, spawnpoints.Length);

        Instantiate(currentWave.EnemiesInWave[enemytoSpawn], spawnpoints[enemySpawnPoint].position, spawnpoints[enemySpawnPoint].rotation);

        waveNumber++;
        enemiesAlive++;
     }
}```
cosmic rain
upbeat furnace
#

so I use waves as scriptable objects so I can customise each wave and well when just having 1 of them in the waves stay at 0 for some reason but when I add Wave 2, it repeats Wave 1 then goes into wave 2... Sorry if that doesn't make sense xD

cosmic rain
upbeat furnace
#

when I used
roundNum.text = "Round: " + currentWave.ToString();
instead of
roundNum.text = "Round: " + waveNumber.ToString();
I got the name of the scriptable object so when the 1st wave started I could see which wave was initiated, then once all the enemies are done it should have initiated the timer which it did then move on the the next wave but it seemed to have initiated Wave 1 instead of 2.

I used this code to increase the wave

{
    
    //increase wave
    if (waveNumber + 1 < waves.Length)
    {
        currentWave = waves[waveNumber];
        currentTime = 10f;
    }
    else if (enemiesAlive > 1)
    {
        //stop spawning once limit is reached for the wave.
        stopSpawning = true;
    }
}```
cosmic rain
upbeat furnace
#

pretty much yeah

cosmic rain
#

You should debug it then whenever you're modifying the value

upbeat furnace
#

thats pretty much what I'm doing though I will say it's weird when I take out waveNumber++; the engine crashes xD

cosmic rain
#

As well as when the it is used

cosmic rain
cosmic rain
cosmic rain
#

Use proper debugging methods and you'll figure it out in no time. You're supposed to be able to debug if you're asking in this channel

upbeat furnace
cosmic rain
#

Don't do that. That's the worst thing you can do to people you're asking help from

upbeat furnace
#

yeah thats my bad xD just picking up programming again

cosmic rain
#

Share the code with the debugs and the result in the console.

#

Since it might be a lot of code, share it all in one code paste link.
!code

tawny elkBOT
upbeat furnace
#

ah cheers! I'll post these rq

sharp blaze
#

Hey guys I'm having a little problem

So I have an overlay canvas and inside of it I have an Image of my character. The character in the UI is a parent of another Image component that is basically acting like an accessory, player can move it around. Later when player confirms the accessory on the character, local ui position of the hat/accessory image is saved and I want to apply that to my character in the world space.

Basically, original character is a SpriteRenderer in the world space and he also has the accessory spriterenderer transform as a child.

How would I convert the screen space local position to the world space local position?

Character sprite is the same in the image and the spriterenderer

cosmic rain
static matrix
chrome trail
#

That's basically it

static matrix
#

how does one do verticies editing?

cosmic rain
upbeat furnace
#

this is after the

{
     //Calculates the number of enemies in a wave to spawn (this is set in the Wave scriptable object)
     for (int waveNumber = 0; waveNumber < currentWave.NumberToSpawn; waveNumber++)
     {
        int enemytoSpawn = Random.Range(0, currentWave.EnemiesInWave.Length);
        int enemySpawnPoint = Random.Range(0, spawnpoints.Length);

        Instantiate(currentWave.EnemiesInWave[enemytoSpawn], spawnpoints[enemySpawnPoint].position, spawnpoints[enemySpawnPoint].rotation);

        Debug.Log(waveNumber);

        enemiesAlive++;
     }```
cosmic rain
#

Also, you should make your logs meaningful like that: "on wave incremented wave number: x" or "on waves reset wave number: x". Just numeric values can make it very confusing especially if you're debugging it in multiple places.

upbeat furnace
#

yeah I need to remember that my bad xD
But yeah I think I know what it's tied to since there are 5 unique values, I believe it is tied to the amount that is spawned which is kinda strange I think I need to untangle my code

heady iris
#

I'm not sure if that happens by itself

chrome trail
heady iris
#

it looks like the meshes are vanishing once the original bounds of the mesh (which is flat ground) go off screen

chrome trail
#

Haven't done it yet though

heady iris
#

Show the code that modifes the mesh

upbeat furnace
#

Okay I found the issue turns out if I have just Wave 1 this code won't initialise:

{

    if (waveNumber + 1 < waves.Length)
    {
        waveNumber ++;
        currentWave = waves[waveNumber];
        currentTime = 10f;
        SpawnWave();
        Debug.Log("Wave: " + waveNumber);
    }
    else if (enemiesAlive > 1)
    {
        //stop spawning once limit is reached for the wave.
        stopSpawning = true;
    }
}```
latent latch
#

Fellow SO enthusiast using them for waves

#

my mate is like "why" and I'm like "what if I want to reuse them later??"

cosmic rain
#

Not quite sure what that condition is testing.

vocal breach
#

can someone help me i changed this little character i made from using character joints to configurable joints and the character fell through its self

upbeat furnace
vocal breach
#

oh nvm i just had to turn xyz motoin to limited and turn collision on

cosmic rain
#

Make sure you don't run this code if you reached the last element

upbeat furnace
#

Well atm I am trying to do is start the wave then use the wave to begin the spawn i figure that way it's easier to debug

cosmic rain
#

It doesn't matter what you're trying to do. You should handle out of bounds correctly. Imagine you have 5 boxes with apples, them you try to take out an apple out of box 6(it doesn't exist). What would happen?

hardy anvil
#

Hey guys I'm trying to make a button object that has a cool down in between presses, but I am unsure on how to do so.

cosmic rain
hardy anvil
spring creek
spring creek
upbeat furnace
cosmic rain
upbeat furnace
#

true xD well I guess I am sort of making progress now

hardy anvil
#

is this how it should be? And if so where do i put my WaitForSeconds() because its only waiting to run my code. Its not really a cooldown.

cosmic rain
spring creek
#

Cooldown could be handled with bools around a wait call. Check the bool before allowing the coroutine to start again (just one simple way to do it)

hardy anvil
#

Thanks I got it working with just a cooldown bool

rigid island
#

also coroutine would've been better than Invoke not sure why you changed it lol

#
 void OnMouseUpAsButton()
 {
     if (farming) return;
     StartCoroutine(Farm());
 }
 IEnumerator Farm()
 {
     farming = true;
     farmerManager.Farm(level, Color);
     yield return new WaitForSeconds(cooldownTime);
     farming = false;
 }```
hardy anvil
rigid island
#

since the function is void (does not return anything) you can just return no value

proper badger
#

Is there like a list of good practices for making a game more moddable

arctic steeple
#

why doesn't the value out equals 6 but 5 ?static void Main(string[] args)

    {

        int value = 5;



        Console.WriteLine("Value before increase: {0}", value);



        IncreaseValue(value);



        Console.WriteLine("Value after increase: {0}", value);

       

        Console.ReadKey();

    }



    static void IncreaseValue(int value)

    {

        value++;

    }
somber nacelle
#

because of the difference between value types and reference types. also this is a unity server, not a general c# server

arctic steeple
somber nacelle
indigo verge
#

I'm pretty sure I could implement this one of two ways, but I wanted to ask you guys for advice and thoughts on this.

I want to use a State Machine to control combat in my Turn Based RPG, and my plan is that each action is its own series of States, OR its own state machine.

This means, for example, when you hit "Sword Swing", the game will load a state machine that asks for a target in one state, moves the player to that target, then performs the attack, making the character perform the state machine's states in sequence.

Would it be better to have Scriptable Objects that just hold a list of states, which are loaded into a State Machine attached to the character, or have a Scriptable Object that holds an entire State Machine, and the player merely switches between those?

thin aurora
#

When it comes to value types, the variable is passed by value and not by reference. This means you make a copy of the value and pass it over to the method. You will not edit the actual initial value because of this

#

Other instances of value types are structs, Vector2, Vector3 and Quaternion, for example. Your IDE usually differentiates value types from reference types when they implement a struct type rather like a class type (like the ones mentioned here)

#

You can fix your code to pass a reference type. Just change the method signature to this:

static void IncreaseValue(ref int value)

And the call to the method:

IncreaseValue(ref value);
#

For clarification, the reason why this difference exists is performance. Especially with vectors the difference is very big when computing values as the reference must be cleared otherwise. This is done with garbage collection and it can impact your game significantly if left done improperly.

leaden solstice
indigo verge
leaden solstice
indigo verge
#

Only one state at a time, yeah

leaden solstice
#

So character should be something that knows what state they are on

#

but if your action needs to override something about states

#

Action should have some way to hook it ig

#

I mean I wouldn't really think this as state machine tho

#

Just list of tasks maybe

indigo verge
# leaden solstice Just list of tasks maybe

Some of those tasks need their own logic and behaviors, though, and need to be able to backtrack, since combat actions need to be able to request UI input and wait for it, and be able to be backed out of with the cancel button and things like that.

leaden solstice
#

What's actually running those state doesn't seem that important in this case

fallow quartz
#

I made an options menu so the player can change resolutions and quality, but when i start a game and then go back to the main menu this settings reset, any idea why?

#

Btw this reset is only at a visual level, but if the res is changed it stays, only happens with the HZ

pastel patio
#

I'm trying to use BatchRendererGroup to make my own "MeshRenderer" for most of the two most recurring meshes (Cubes & DoubleFacedQuads)

#

However what troubles me a lot is how I'm meant to sync the transformations of the Transform's transformations with the BGR instances

#

How am I meant to sync all the data? I could try SetData and calculate the offset for each individual movement however... Well, I can bet that the performance implications of SetData is nothing like that of just copying stuff into an array

#

I can't use GraphicsBuffer.LockBufferForWrite either cus Unity crashes if I create the buffer for BGC's instance data with that flag on

#

So the last resort in that case would be SetData once every frame, it would seem

#

Since there're prone to be many cubes moving... SetData once for each cube's movement is really bad, Setting once per frame for everything might be costly too but maybe it's not as bad

pastel patio
#

Nvm overlooked something- In one of the articles they recommend making one such buffer on the cpu

#

Still needs to perform SetData every frame... Hopefully it's for some reason extra performant copying the whole buffer over

frail meteor
#

How do I convert a base64-encoded audio string I receive from a websocket message into an audioclip to run at runtime?

knotty sun
topaz dock
#

Has anyone seen behaviour like this in the profiler before? The rendering numbers keep dropping to 0 and back to normal again?

slate imp
#

Hi, I have a reasonably big unity project with around 30 scenes, and made a big refactoring process, the thing is, i have added a lot of serialize fields, i want to see for each game objects if he has some fields with none values inside in all scenes (or minimum one scene)

Is their someone that could help me finding a tool or something like this ?

fallow quartz
#

Screen.fullScreen works properly? Because im trying to update an image to be enabled or disabled depending on if the game is fullscreen or not but its not working

thick terrace
errant shore
#

Hi, my plan in the function MoveChildToParent is to delete the desired item from the string, but for some reason it randomly deletes another item
https://gdl.space/enoyuqojeq.cs

heady iris
#

Are you looking for fields that have nothing assigned to them?

slate imp
# heady iris I don't understand what you're asking for

I have added serialize fields to some scripts, and since they are used in a lot of scenes and objects i want to edit all of them and not forget any, also since i changed multiple script i could miss a script

the idea is to have some tools that will find each object that have empty fields

heady iris
#

I've written code to do this, actually

#

it's still very rough, but maybe you can use it

slate imp
heady iris
#

https://gdl.space/idiyidabob.cpp

This is most of the code. You call ReferenceValidator.ValidateOneObject with any object, as well as an optional Unity object as a context for the log items

#

it also takes a visited hash set. you can use that to remember which fields you've already alerted as being null, so that if you validate many objects, you won't get duplicate warnings if they all reference the same object that has a missing field

#

Here's an example of how I used it in my code

#
[ContextMenu("Validate References")]
public void ValidateReferences()
{
    HashSet<object> visited = new();

    ReferenceValidator.ValidateOneObject(this, this, visited);
    ReferenceValidator.ValidateOneObject(defaultBrain, this, visited);
    ReferenceValidator.ValidateOneObject(defaultLocomotion, this, visited);

    foreach (var module in GetComponentsInChildren<Module>())
        ReferenceValidator.ValidateOneObject(module, this, visited);
}
#

notice how I'm passing the same visited hash set to everything

#

The validator will stop when it sees a class from a different namespace. I did that because third-party components had many fields that could safely be null, and I didn't want to have to go modify them and add my [MayBeNull] attribute

#

For each null field, it logs the path it took to get to the field. The log message's context is the closest unity object

#

If it went into a prefab, clicking the log will just highlight the prefab. Running the validator with the prefab open (sometimes) highlights the component properly

#

If you want to validate objects in scenes, you'll need to open the scene and then use FindObjectsByType or something similar to scan for the component you're interested in

slate imp
#

Thanks a lot i'll try making it into a plugin

split orbit
#

Where is this links generation section?

#

https://www.youtube.com/watch?v=WBXti5pea88 OK this video has an example of it

Part 5 of this series on Unity pathfinding to look at how to link different nav mesh surfaces together.

--
Support our tutorials on Patreon for access to our finished projects and vote for new topics.
https://www.patreon.com/tableflipgames

--
Table Flip Games
We are a team of specialists in video game development and technologies with experien...

โ–ถ Play video
heady iris
#

I wonder if they forgot to port that page over

#

The navmesh stuff mostly moved into a separate package

knotty sun
#

tbh the old Github NavMeshComponent documentation is far better than the new AI.Navigations ones and there is very little functional difference

split orbit
#

Unity moment

fallow quartz
#

How unity handles toggles to make the image inside dissapear?

gray mural
gray mural
gray mural
fallow quartz
#

the toggle is always activated (which is what i want if the screen is fullscreen)

#

but even if my screen is windowed

#

the toggle is activated

gray mural
#

Alright?

fallow quartz
#

wdym by alright hahaha

gray mural
#

I don't seem to get your question

fallow quartz
#

the toggle is used to change between windowed and fullscreen. When i click it the image inside dissapears so only the borders are left. I want the image inside to be on if the gameis fullscreen and to be off if its windowed

#

The problem comes when i activate windowed mode, which leaves the image inside off

#

but if i go to another scene and come back

#

even tho im still in windowed mode

#

the image is activated again

fallow quartz
devout silo
#

i have a lightning wich i want will follow after my swipes. i want to create a line from 2 points (start swipe and end swipe) and make the lightning follow the line thaht create. help?

dense crow
#

do u guys have any idea about spawn manager? , like in a endless runner game, how to manage what is the next map to spawn ?, my idea is base on the score, i will add maps to a possible list then choose a random map

devout silo
dense crow
#

UnityChanwow i am asking, i don't have enough experience to teach anyone, sryy

devout silo
#

no i mean, you can search for a toturial for this

#

there is gotta be

#

here

#

take

#

Hey friends! Let's learn how to generate infinite levels and platforms in Unity with Procedural Generation! This is a follow-up to a video I made about Subway Surfer, and I thought this would be a good overview on how procedural generation works.

๐Ÿ‘พ Join the Discord! https://discord.gg/MYAujpE4xG

๐Ÿซถ Access Code Files and Projects! [patreon.com/...

โ–ถ Play video
dense crow
heady iris
#

i dunno, pick one at random

#

that's a game design decision

dense crow
gray mural
fallow quartz
# gray mural Yes. The image inside you're talking about is a `Checkmark`. Simply reverting yo...
 {
     // Comprobar si los valores de la resoluciรณn estรกn almacenados en PlayerPrefs
     if (PlayerPrefs.HasKey("ResolutionWidth") && PlayerPrefs.HasKey("ResolutionHeight") && PlayerPrefs.HasKey("RefreshRate"))
     {
         int width = PlayerPrefs.GetInt("ResolutionWidth");
         int height = PlayerPrefs.GetInt("ResolutionHeight");
         int refreshRate = PlayerPrefs.GetInt("RefreshRate");

         // Establecer la resoluciรณn guardada
         Screen.SetResolution(width, height, Screen.fullScreenMode);
         Application.targetFrameRate = refreshRate;
     }
 }```
why my fps doesnt cap at my HZ chosen in the dropdown for the resolutions?
leaden ice
fallow quartz
rigid island
gray mural
#

Also I don't think there is a need to check for all 3 strings being in PlayerPrefs, as you shouldn't access one of them without having the other two. Am I right?

fallow quartz
gray mural
#

Why don't you consider printing it?

fallow quartz
gray mural
fallow quartz
#

cause they are not getting created

gray mural
#

They should be created if you do this via code. The shouldn't if you don't.

fallow quartz
#

like it happens maybe 1/10 times

#

If i change res, execute level 1, go back to the main menu scene and check the res sometimes it gets automatic screen size

rigid island
#

time to learn json

gray mural
gray mural
slim trail
#

hi

slim trail
#

someone know how to stop transmit speed between two objects when one have big force?

gray mural
# fleet tide Better ahah !

Alright, now this looks a bit more lively. Now you should consider making the unique names for the Spells ๐Ÿ˜‰

gray mural
fleet tide
gray mural
devout silo
#

I explained

fleet tide
fleet tide
gray mural
slim trail
spring creek
#

Assuming the latter, it would depend on how movement occurs.
You could make the enemies kinematic,
or add a larger trigger area around the enemy and detect then destroy the bullets before they actually collide,
Or disable collisions between the enemy and bullet layers and use spatial queries instead

Just depends on what you want

gray mural
slim trail
spring creek
#

OnCollisionEnter

slim trail
#

I tried to do that, but it doesn't detect collisions

spring creek
#

Do one of the two objects have a dynamic rigidbody?
Do both have colliders, and NEITHER are a trigger?

slim trail
#

eee

#

but you said it SHOULD be trigger

spring creek
#

If you want to use OnCollisionEnter, then neither can be a trigger

#

If you want to use OnTriggerEnter then exactly one must be a trigger

slim trail
#

so @gray mural sayed that

spring creek
#

Which would mean there are no physical collisions.
Is that what you want? Then go with OnTriggerEnter

If you want them to physically collide, and just not bounce, then OnCollisionEnter but destroy the bullet

It is entirely up to you

gray mural
gray mural
sly chasm
#

mb what is the InvalidOperatoinError

#

thanks

knotty sun
#

the last 3 words of the message tells you

sly chasm
#

sorry if i'm dumb

knotty sun
#

you are trying to use an Animator without assigning an Avatar

sly chasm
#

alr ty

spring creek
sly chasm
sly chasm
#

sorry for the bother

knotty sun
#

Somewhere you have an Animator component attached to a gameobject. You need to supply it with an Avatar

sly chasm
knotty sun
sly chasm
#

It links to a script I think?

knotty sun
heady iris
#

Clicking once on the message may highlight the source of the error in the hierarchy

sly chasm
#

I go to the line [996]

heady iris
#

once, not twice

#

double clicking opens your code editor

#

(and you should do it while the game is running)

sly chasm
#

Ah, ok

#

i'll try that

heady iris
#

if that doesn't work, search for t:animator or t:mrider while the game is running

sly chasm
#

btw it highlights the player

heady iris
#

okay, so the player probably has an Animator or MRider component on it

halcyon steppe
#

Hi, I am currently writing a movement script and I am trying to implement movement on a slope. I got everythign working except for that I always get stuck on the transition from a flat piece of ground to a slope. How do I fix this?

If I sprint at the slope or jump on it it works fine but the transition while walking doesn't work.

In the screenshots you can see how I detect if I am on the ground and if I am on a slope as well as a Screenshot from inside the engine with my scene.

sly chasm
spring creek
#

Or do multiple rayasts

halcyon steppe
#

I will look into that, thank you very much

velvet pebble
#

that doesn't really seem to address the main problem

#

I agree that you should use a spherecast rather than a raycast to determine if you contact the ground

#

but what do you mean by the transition while walking not working

heady iris
#

i presume OnSlope doesn't become true and they get stuck

spring creek
#

I assume the mean the common issue of when you start to go up the slope, the player lifts up, and you no longer register as grounded. (Or OnSlope in this case, as fen said)
But yes, that was an assumption

halcyon steppe
#

Fen is right, OnSlope doesnt change to true initially

#

Is there a way to display the sphereCast? Like Debug.DrawRay but for the sphere?

spring creek
#

Welll... there is Gizmos.DrawSphere

Or Debug.DrawLine and approximate what you need of the sphere

halcyon steppe
#

this is the situation at the bottom of the slope

heady iris
#

yes: the physics debugger!

pastel patio
#

Is it a good idea normally to use NativeArrays?

heady iris
pastel patio
#

I'm using it in BatchRendererGroup

heady iris
#

note that only newer versions of unity have the query visualizer, iirc

pastel patio
#

More specifically, to keep a local copy of the instance data

#

I practically have to use the functionality to write a bigger type into a collection meant for a smaller type

heady iris
#

you'll have to show me what you're doing

halcyon steppe
#

Thank you so much

spring creek
pastel patio
#

This is the place where it really clashes if I try to use a normal array

Span<PackedMatrix> objectToWorldMatrices = new Span<PackedMatrix>((byte*)localDataBuffer.GetUnsafePtr() + byteAddressObjectToWorld, maxInstances);
Span<PackedMatrix> worldToObjectMatrices = new Span<PackedMatrix>((byte*)localDataBuffer.GetUnsafePtr() + byteAddressWorldToObject, maxInstances);
Span<Color> colors = new Span<Color>((byte*)localDataBuffer.GetUnsafePtr() + byteAddressColors, maxInstances);
#

Uh, lemme just show the whole code

heady iris
#

oh, yes, you absolutely have to use a NativeArray when packing different kinds of data into a buffer

pastel patio
#

This is my script

#

Uh, after I randomly swapped the native array for an array, just pretend localDataBuffer is still a NativeArray

fallow quartz
halcyon steppe
#

IT WORKS, you guys are legends! thank you again, Spherecast was the way to go and the physics debug is the best thing i have ever found!

pastel patio
#

Although... To be fair pretty sure it's cus I forgot to dispose and ended up creating a memory leak... haha...

#

Still, would this NativeArray be eating up the stack?

heady iris
#

no, it's heap-allocated

#

a stack overflow is probably just infinite recursion

pastel patio
#

It wasn't recursion... Maybe it's when you start playmode they allocate a lot of stuff on the stack

heady iris
#

stack overflows are almost always caused by infinite recursion

#

show the stack trace

pastel patio
#

While the heap is kinda blown up thanks to the memory leak

heady iris
#

this is something in the UI breaking

pastel patio
#

Honestly... It was probably a side effect

#

Not the first time errors say this but it's that

#

The crashes stopped as soon I added localDataBuffer.Dispose() in OnDestroy

#

That's why I'm guessing that the heap was very much packed and then enter playmode made it crash

gray mural
half saddle
#

Does a visual effect clean up itself when all particles lifetime has passed or do I need to clean it up myself?

fallow quartz
gray mural
fallow quartz
gray mural
fallow quartz
#

in the editor theres no resolutions

gray mural
#

It still won't give you an error when trying to assign it

pastel patio
#

If "CleanUp" means destroy

#

You can also set it to Callback, never used it but I think that it should allow you to make something execute when all particles expire

fallow quartz
gray mural
fallow quartz
gray mural
#

So what's the problem then?

fallow quartz
#

is just random

half saddle
#

I want to make sure compute shaders aren't still running in the background after all the particles have disappeared

pastel patio
#

Seems kinda absurd if they still do, it's a tool meant to be highly performant. Although I can't be sure about this one

#

Uh, although, in my case at least it ain't uncommon to still keep the memory to avoid re-allocating everytime

#

But that things are still running is another story

half saddle
#

I noticed in the scene if I play the visual effect without reinitializing it some attributes of the particles existed as if they had been going along this whole time, but that might just be a matter of the system knowing when they original were spawned and lerping the values from there, not updating while they had disappeared

haughty ember
#

I'm working on a game that involves both the player controlling a car as well as AI cars. I got a somewhat decent physics system working on my player car controller, but I know I'd like to make changes to the car physics in the future. AI cars should use the same physics. So naturally, I'd like the physics to be split into its own script rather than having a lot of duplicated code between the player controller and AI controller scripts. I'm struggling with 2 possible approaches. The first is making a base class "CarController" that the PlayerCarController and AICarController classes can inherit from. The other approach is to just make a separate CarPhysics script that can be called by the player car controller and AI car controller (for example, they could call "ApplyAcceleration", which would be movement input from the player and whatever input the AI decides for the AI). I tried the inheritance approach but it got kind of weird when considering the 2 separate inputs, does the CarPhysics separate script sound like it could possibly be better?

pastel patio
#

if you know all the things you would need to interact with and how, a separate script is cleaner imo

somber nacelle
#

separate components, where the input from the player and the input from the AI can be added along side the component that actually applies the input

pastel patio
#

Just wanna mention that a separate script can also cause you a bunch of hassle, if the two was meant to be more complexly coupled or stuff

#

I've had this struggle with my Health before- IHealth interface or Health component?

haughty ember
# pastel patio if you know all the things you would need to interact with and how, a separate s...

So you think the car physics separate script is cleaner then? For more context, yeah the current base car controller script is just applying a lot of forces (such as suspension, natural deceleration) each fixed update. The only 3 things it really needs input from an outside entity (player or AI) is acceleration, turning, and manual deceleration. So I'd imagine I can just call these from the controllers like "ApplyAcceleration, ApplyTurning, etc"

pastel patio
#

Yeah, if those are the only things you'd be good keeping them separate

#

I forgot what the deal was but it got pretty annoying when the health was a separate component from the creatures, so... Sometimes separate components ain't really optimal

haughty ember
#

Ok, thanks for the help that does seem better, was mostly finding inheritance examples online so just wasn't sure. I guess it does depend on the situation, I usually use health as a separate component but I also haven't made anything all that complicated yet to be fair

pastel patio
#

Inheritance gives a hell of a lot of control imo, drawback is how messy the inspector can become and if you don't watch out how messy the script can become too

vagrant moon
#

its always case by case, I usually go with separate script for reading inputs, and common scripts that could "handle" that input. than AI can have its scripts to provide its own input

haughty ember
#

Yeah I think inheritance would work here if there weren't so many implemented physics functions in the parent class. But there's just so much going on in the base script that the child classes never override that it seems like it should just be its own script

pastel patio
#

Yeah, good luck Fossil

#

Imma go back to my dungeon

gray mural
fallow quartz
gray mural
#

Haven't used the tiles much

neon harbor
#

hello, im having an issue with accessing animation rigging components through scripts

#

i have the package installed in my editor

somber nacelle
#

try regenerating project files and restart visual studio

neon harbor
#

doesnt work

somber nacelle
#

are you using asmdefs in your project

neon harbor
#

oh

#

damn

#

you are right

#

it works now, thanks

valid solar
#

Okay so im super confused, if I can have a default virtual function in an interface, add it to a class, but not call the default implementation, what else would they be used for?

vagrant moon
#

you can cast your object to this interface type and call it than

void void
#

Hi, I'm currently trying to wrap my head around DOTS & ECS.
I'm prototyping a tower defense game so I've got lots of entities that will share the same data (waypoints along a path from their spawn point all the way to the "exit"). I've tried making use of ISharedComponentData to store the waypoint positions (as a list of float3) but I couldn't manage (having a float3[] inside a ISharedComponentData didn't sit right for some reasons). Many paths can exist so all entities might not follow the same path.
So I've just encountered BlobAsset and they seem to be one of the right tools to use in this case but I'm wondering about how to actually use them, should I:

  • Store a BlobAssetReference (in a ISharedComponentData) that's created at bake time and Unity will figure that a lot of other entities share the same content hence use the same pointer thanks to some BlobAssetStore magic ?
  • Store a BlobAssetReference (in a ISharedComponentData ) from a map of BlobAssetReference that's created at GameObjectConversion time ?
  • Do something else that's more idiomatic of BlobAsset and DOTS ?
void void
#

Noted, thanks

valid solar
somber nacelle
#

don't treat interfaces and default interface methods as inheritance and it won't feel weird to do that at all

valid solar
spring creek
#

You can do a lot of terrible ideas

#

It is called flexibility

fallow quartz
#

only problem is when I close the game windowed

somber nacelle
# valid solar I mean why let me do it then real talk

just because you can treat it like that, doesn't mean you should. interfaces are not a substitute for multiple inheritance and should not be treated as such. interfaces are to provide a common interface to interacting with different objects

fallow quartz
#

Then, after opening again I only get 3 resolutions and without the HZ

valid solar
somber nacelle
#

there is no "best way", and what you've described can be achieved in a number of ways, none of which require you to try and use interfaces as a sort of multiple inheritance situation

astral oriole
#

For some reason this code doesn't return anything when on my mobile device, is there something I may be missing?

heady iris
#

are you sure it's being given valid data on your phone at all?

astral oriole
#

yeah the correct data gets passed

#

but nothing comes out for some reason

#

works perfectly fine on desktop though :/

silent tapir
#

Should I use scriptable objects or whats the best way for a modular gun system? with fireRate, damage, rounds, other characteristics, etc.

heady iris
#

scriptable objects are useful for storing data as an asset

#

useful for storing parts of a weapon, perhaps

#

but the actual definition of the weapon can be a plain old C# object

fallow quartz
#

Is there any way too do something in an audio so it sounds like if it was far far away?

#

or behind a door

heady iris
#

there are audio filter components you can add to the same object as an audio source

#

a reverb filter plus a low-pass filter can give you a "muffled" effect

rigid island
somber nacelle
#

ScriptableObject and Plain Old C# Object

fallow quartz
quick token
#

does anyone know why i cant change an objects parent and position/rotation on the same frame?

AnchorPoint.transform.up = plcCon.ConnectionPoint[1].TransformDirection(Vector3.up);
placing.transform.SetParent(AnchorPoint.transform);
AnchorPoint.transform.up = -conPoint.up;

this code works but it it doesnt rotate the child and parent. it only rotates the parent

same code but without the messy variable names:

A.up = B.TransformDirection(Vector3.up)
C.SetParent(A)
A.transform.up = -D.up

A's position/rotation is correct but C's is not

#

basically im just rotating it, adding a child and rotating it again

#

for some reason unity doesn't seem to rotate the child

#

nvm, I'm dumb

#

i forgot to delete a line i added like 3 days ago ._.

heady iris
#

The dry level is how much of the un-processed audio is kept (measured in decibels, so 0 is 100% strength)

silent tapir
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Weapon : ScriptableObject
{
    
}
heady iris
#

a "POCO" being a "plain old C# object"

#

a class that isn't inheriting from MonoBehaviour, ScriptableObject, etc.

#

You store the weapon definition as a Weapon. If you want to make a weapon preset, you make a WeaponPreset scriptable object that stores a Weapon

rigid island
silent tapir
rigid island
heady iris
#

You can only define one MonoBehaviour or ScriptableObject per script file.

#

You can wedge other classes in, if you want

silent tapir
#
using UnityEngine;

[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapon")]
public class Weapon : ScriptableObject
{
    public string weaponName;
    public int maxAmmo;
    public float fireRate;
    public float reloadTime;
    public GameObject weaponPrefab;
    public AudioClip fireSound;
    public AudioClip reloadSound;
}```
silent tapir
rigid island
# silent tapir How so?

Seperation of concerns

public class Weapon : MonoBehaviour
{
    public WeaponData WeaponData;
}
public class WeaponData : ScriptableObject
{
    public WeaponStats Stats;

    //other sutff like
   //AudioClip FireSoundl;
    //etc

}
public struct WeaponStats
{
    public float FireRate;
    public int MaxAmmo;
    //etc.
}
heady iris
#

indeed

#

Weapon is the actual component in the game world

silent tapir
#

So, why would I separate the WeaponStats in two diferent categories?

silent tapir
heady iris
#

I'd rearrange it a bit

rigid island
#

well no reason to mix Stats data , with AudioClips or other assets

#

just personal preference

silent tapir
#
using UnityEngine;

public class Weapon : MonoBehaviour
{
    public WeaponData WeaponData;
}

[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapon")]
public class WeaponData : ScriptableObject
{
    public string weaponName;
    public int maxAmmo;
    public float fireRate;
    public float reloadTime;
    public GameObject weaponPrefab;
    public AudioClip fireSound;
    public AudioClip reloadSound;
}```
heady iris
#

so that WeaponData is also a plain old C# object; you can create SOs to hold a WeaponData as a "preset", as well as other types to hold stuff like muzzle flash definitions

rigid island
#

easier to copy the whole WeaponStats to modify it on the instance

heady iris
#
public class MuzzleFlash : ScriptableObject {
  public ParticleSystem particleSystemPrefab;
}
#

(you might add more fields later)

silent tapir
#

hm interestin

rigid island
#

yeah it works fine

heady iris
#

not if you put both in the same file

#

but otherwise yes

silent tapir
heady iris
#

However, if you want to be able to modify the weapon as you play the game, you probably don't want to shove all of the stats into a scriptable object

#

if two places use the same scriptable object (e.g. you have two of the same weapon type), modifying one will wind up modifying the other

#

use ScriptableObjects to hold definitions of things, like a kind of muzzle flash

dense surge
#

Whereโ€™s the channel to get help

rigid island
#

indeed , thats why I made poco on it to copy basestats and then modify

rigid island
silent tapir
#

I don't use pocos much

heady iris
#

you just make a class

#

mark it [System.Serializable] so you can serialize it in the inspector

dense surge
silent tapir
heady iris
#

i don't know what a "gun holder" is here

rigid island
heady iris
#

Weapon represents the actual weapon in your game world.

silent tapir
#

but I can just put it on the gun GameObject

rigid island
#

well the model shouldn't be your root object anyway

rigid island
silent tapir
#

ok, it ain't just asking

rigid island
#

looks fine

silent tapir
#

now how should I access the weaponData properties properly in the weapon.cs script

rigid island
#

so yeah Lets say I made weaponstats a struct,
I can just do ```cs

public class Weapon : MonoBehaviour
{
public WeaponData WeaponData;
public WeaponStats currentStats;
private void OnEnable()
{
if (WeaponData != null)
{
currentStats = WeaponData.Stats;
}
}
public void IncreaseFireRate(float amount)
{
currentStats.FireRate += amount;
}
}```
on the weapon for example

silent tapir
#

wheres the struct

rigid island
#

on the SO

#
public struct WeaponStats
{
    public float FireRate;
    public int MaxAmmo;
    //etc.
}```
silent tapir
#

oh shit I see

#

mb lol

#

whats the weaponData do then

rigid island
#

but yeah you would make them System.Serialiazable so they can be modified in inspector

silent tapir
#

oh its the base model to be copied

#

i see okay

rigid island
silent tapir
#

where is the class WeaponStats supposed to be initialized?

rigid island
#

it makes it so you can just swap an SO and your weapon is now different

silent tapir
rigid island
silent tapir
#

no i mean where is it defined

rigid island
#

put it in a different file, doesn't matter

#

like I said this is fine, is just more annoyance to copy individual fields than a whole struct

#

if you plan on modifying those stats that is

#

if not then yeah don't worry about it

lusty gull
#

hello everyone, i need some help building my unity project. I need to make a build with il2cpp for windows. Right now i only have access to a linux machine, and i can't find a way to build for windows using il2cpp backend. I already tried using a virtual machine but the build gets stuck. Does anybody know a way to build for windows from another platform?

rigid island
silent tapir
# rigid island Unity Cloud offers a service like that https://build.cloud.unity3d.com/landing/
using UnityEngine;

[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapon")]
public class WeaponData : ScriptableObject
{
    public string weaponName;
    public int maxAmmo;
    public float fireRate;
    public float reloadTime;
    public GameObject weaponPrefab;
    public AudioClip fireSound;
    public AudioClip reloadSound;
}

public struct WeaponStats
{
    public WeaponData weaponData;
}``` this look correct?
#

or do I have it backwards

#

I think I do

#

idek

rigid island
#

what did you do..

#

look at my examples from before lol

silent tapir
#

well its confusing because you have the same variables in each one

lusty gull
#

try putting maxAmmo fireRate and reloadTime in WeaponStats, then declare WeaponStats inside WeaponData

silent tapir
#

or they are both storing variables that are relevant to just the gun

rigid island
# silent tapir
[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapon")]
public class WeaponData : ScriptableObject
{
 
    public WeaponStats WeaponStats;
    public GameObject weaponPrefab;
    public AudioClip fireSound;
    public AudioClip reloadSound;
}
[Serializable]
public struct WeaponStats
{
    public string weaponName;
    public int maxAmmo;
    public float fireRate;
    public float reloadTime;
}```
silent tapir
#
using UnityEngine;

[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapon")]
public class WeaponData : ScriptableObject
{
    public WeaponStats weaponStats;
}

public struct WeaponStats
{
    public string weaponName;
    public int maxAmmo;
    public float fireRate;
    public float reloadTime;
    public GameObject weaponPrefab;
    public AudioClip fireSound;
    public AudioClip reloadSound;
}```
silent tapir
#

wait whats the point of separating them

rigid island
#

ideally you only want value types inside struct

silent tapir
#

they are both useful to the gun

rigid island
#

I would only seperate if you plan on modifying the stats

silent tapir
#

oh bc the fireSound doesn't change?

somber nacelle
#

the prefab and sounds are not "stats"

silent tapir
somber nacelle
#

they can be considered part of the data for the weapon, but they are not the weapon's statistics

silent tapir
#

so idk what the point of separating them are

lusty gull
fallow quartz
silent tapir
rigid island
#

reloadSound sounds as stats makes no sense to me

#

stats are numbers

silent tapir
#

What if I am changing the gunModel because I am adding a silencer to it. but only for one person.

rigid island
#

if you change it on a SO it will change it for everyone who has that same SO

silent tapir
#

what if I am changing the sound for a silencer? @rigid island

rigid island
#

look for example, If i want to change fireRate Im only doing it on this weapon.

#

Im not changing it for everyone that has this weapon

silent tapir
#

exactly whats wrong with changing the audio due to a silencer then>?

lusty gull
rigid island
silent tapir
#

on the currentStats

rigid island
lusty gull
#

also, you can use Instantiate on scriptable objects to get a copy, and then reassign the new one

rigid island
#

thats why i dont mix them in struct as much

silent tapir
#

ah okay

rigid island
#

they cannot be copied, only bring the original with you

heady iris
#

getting a bit lost in the weeds here

silent tapir
#
using System;
using UnityEngine;

[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapon")]
public class WeaponData : ScriptableObject
{
 
    public WeaponStats WeaponStats;
    public GameObject weaponPrefab;
    public AudioClip fireSound;
    public AudioClip reloadSound;
}
[Serializable]
public struct WeaponStats
{
    public string weaponName;
    public int maxAmmo;
    public float fireRate;
    public float reloadTime;
}``` there
rigid island
heady iris
#

if you want to allow upgardes to have effects on the weapon's visuals and sounds, you need to make it so that each "modification" to a weapon gets a chance to modify the weapon's vfx/sfx

#

for example, each modification could be allowed to attach extra models to the weapon

silent tapir
#

ah alr

heady iris
#

a "silencer" modification would add models to each barrel on the weapon

silent tapir
rigid island
#

pretty much

heady iris
#

and, when you fire it, the silencer would override the audio clip that gets used

#

it's a non-trivial problem

#

I did something like this during a game jam once

rigid island
#

WeaponName might have to stay in WeaponData

#

since you're not gonna be changing that

silent tapir
#

could

#

Upgrade it to Legendary Glock

#

for e.g.

heady iris
#

modifiers could also prepend or append text, yes

latent latch
#

That would be another field

heady iris
#

"silenced armor-piercing glockinator"

silent tapir
#

lol

latent latch
#

make yourself defaults and only ever read from them

rigid island
# silent tapir

yes, you would not modify anything on this one, only a copy of them

silent tapir
#

so I could change these ones tho

rigid island
#

those can be mutable no problem

#

as they are a copy of the original

silent tapir
#

bruh wtf

silent tapir
rigid island
#

yes that REGEX preventing spam

silent tapir
#

ah okay

fallow quartz
#

btw @heady iris do you know why in this code:
https://hastebin.com/share/olupagaxop.csharp

when i restart the game while being on windowed resolution changes for some reason

dense surge
#

Can you download unity on a school chromebook or chromeOS just wondering

spring creek
#

I mean, you could probably download the file. But not install it

dusk apex
full canopy
#

I have several scripts that work in tandem to make a very good VR bolt-action handler. I updated some things and it no longer works, for some unseen reason

They are also executed in a specific order:
(1) GoTo: tracks one local rotation axis and any/all of the position axis to another object. In this case, rotates toward my hand along only the local z axis, and also moves only along the local z axis toward my hand.
(2) TransformLimiter: flag enum to allow limiting of x/y/z rotation and x/y/z position. clamps the local rotation/position for each enabled axis to a low & high number in the inspector
(3) BoltAction: dumbed down, changes the relevant (in this case onl z rot and z pos) low and high clamp ranges when the bolt is in a certain area.

when TransformLimiter is disabled, GoTo accurately follows my hand along the z rotational axis. no issues with tracking and there is no unaccounted for offset. Its local rotation in the inspector also falls within the range limited by TransformLimiter
when TransformLimiter is enabled, the object snaps to its high range value and no longer rotates at all.
the BoltAction script seems to have no effect at all.

below is relevant portions of code

#

GoTo


//rotation
. . . . .
if (transformConditions.HasFlag(toggles.RotZ))
{
    newAngle.z = Mathf.Rad2Deg * Mathf.Atan2(relative.x, relative.y) * -1;
    from.localEulerAngles = new Vector3(from.localEulerAngles.x, from.localEulerAngles.y, newAngle.z);
}```

TransformLimiter

//rot
. . . . .
if (limits.HasFlag(Toggles.RotZ))
{
limitedTransform.localEulerAngles = new Vector3(limitedTransform.localEulerAngles.x, limitedTransform.localEulerAngles.y, Mathf.Clamp(limitedTransform.localEulerAngles.z, zRotationLimit.x, zRotationLimit.y));
}```

#

oh btw originalReference has the exact same starting transform as the object with these scripts

waxen blade
#

I'm trying to change the color of my played particle system with a script to a green color. But when it plays, it's gray. If I change my particle system's color using the inspector, 51, 204, and 40 is the correct colors for green. What am I doing wrong?

    public void PlayParticle()
    {
        ParticleSystem currentParticle = Instantiate(gas, foo.transform);
        var main = currentParticle.main;
        Color color = new(51, 204, 40);
        main.startColor = color;
        currentParticle.Play();
    }
dusk apex
waxen blade
#

Oh.. that's unexpected.

#

I was trying to set it to the RGB values that go up to 255. Is there a different method I can use?

dusk apex
#

The Color32 constructor would take values between 0 and 255

#

Color color = new Color32(...)

waxen blade
#

Hmmm maybe I won't be able to use Color32.

dusk apex
#

Lookup what a min max gradient is

waxen blade
#

It's basically a color range right?

dusk apex
#

Look through the docs. It returns a Color but it's something more. There are properties at the bottom of the page that you might be interested in.

This contains two Gradients, and returns a Color based on ParticleSystem.MinMaxGradient.mode. Depending on the mode, this may return the value randomized.

waxen blade
#

I decided to go back to Color and divide by 255 to get the same number, but one that Unity accepts, and it works.

Color newColor = new Color(51f/255f, 204f/255f, 40f/255f);
main.startColor = newColor;
#

I have a lot to learn about particle systems though, and colors are clearly a staple of them, so I'll look through the article you sent.

dusk apex
waxen blade
#

Thanks for helping me get to the solution Dalphat.

dull cedar
#

Hey guys I need some help, I have a 2D rigged character with an animation. I want to create a character editor at runtime, where I can swap out the sprites for the head, torso, legs etc. But when I change the sprite of the head it is no longer attached to the rig and the character becomes unusable. I do have 'Auto Rebind' checked as well. Is thre something specific that I am missing?

leaden ice
#

Are you using skeletal animation?

dull cedar
dull cedar
dull cedar
leaden ice
#

But who is publishing the things to be downloaded?

#

You? Or users?

dull cedar
leaden ice
#

If it's users, this doesn't seem possible because how do you expect the sprites to become rigged (weight painted etc)

#

Maybe if you have them author the sprites with Unity, rig them, and upload them as AssetBundles?

#

If it's just like, an image file, that doesn't contain enough info to do skeletal animation

dull cedar
leaden ice
#

Not sure where you expect to get the animation rigging data from then

#

The alternative here is to use spritesheets/multiple sprites without any deformation

dull cedar
leaden ice
#

Well someone has to rig it.
Either build a tool that lets your users do the rigging
Or build something with AI???

dull cedar
#

Is there a way to generate the geometry at runtime?

leaden ice
#

but again

#

I don't see how you could take an arbitrary user-provided image and know how to generate the geometry procedurally

#

The only feasible solution I can think of is training an AI to do it.

dull cedar
full canopy
tulip frigate
#

I've some problem for a while now, maybe someone here can solve it:

I'm working on a simple input script using Input.GetAxis for horizontal and vertical movement in a 3D game. The player object moves with a Rigidbody based on this input.

Before actually moving the player object (using rb.velocity = ...), I'm saving the input vector to a list so I can "replay" the input later. This works fine: I can move normally and replay the input to replicate the same player movement.

The problem arises when the player object physically interacts with other Rigidbody objects in the scene (e.g., a new Cube object with a Rigidbody). Here's what happens:

When I push the cube around for a few seconds (like a soccer player dribbling a ball) and then replay the input, the playback behaves differently. The replayed player object ends up slightly off from the original position, losing the cube it was pushing, and finishes at a different location than expected.

Important to note that the playback itself does actually get the same result every time; I mean, I can replay it over and over and the results will be 100% consistent and identical, even with physics interaction.

Any ideas?

full canopy
#

it might just be unavoidable floating point error if the playback you made is, at the base level, doing the exact same thing you do when you use input. weird issue

#

it could also be the execution order being slightly off now that i think about it

#

some things execute instantly and some on fixed update

#

so depending on your implementation it might be fractions of a frame off, but enough to cause a difference

#

ive had that issue come up so so many times making my vr game, things happen in between frames but it still affects the physics output

latent latch
#

replay by exact coordinates, not by functionality of the physics system

#

could maybe record yourself a timeline and replay it as an animation clip

full canopy
#

its possible using physics is necessary for scarlet

#

there might be ways you can fake it though if you want the effects of physics on things

latent latch
#

just lerp it all, it'll probably be fine

full canopy
#

im saying the rigidbody might be necessary

#

like to push stuff around, bounce, slide, whatever

tulip frigate
#

Yes physics are crucial for my purpose, but how is the physics interactions are always the same when replaying the same playback over and over?

full canopy
#

unity's physics engine is pretty good, so most of the time if you have the exact same starting conditions, youll get close to the exact same ending conditions

tulip frigate
#

But If order of execution might be the problem, why doesnt it affects this case?

full canopy
#

well because the order would always be the same

latent latch
#

I'd try messing with the detection modes maybe

#

could be that messing with the second rigidbody then does a sweep for other rigidbodies

full canopy
#

quick question, are you recording the input on update or fixed update?

tulip frigate
#

Input recording on update and movement itself (changing the rigidbody) happens on fixedupadate

full canopy
#

ok try adding to the input recording list on fixed update instead

#

that way it is recorded at the same rate its later re-played

tulip frigate
#

Yea thats what happen atm

full canopy
#

unfortunately i told myself id go to bed almost an hour ago and here i am still so im heading out, hope you find the help u need

tulip frigate
#

Lol np , good night

tulip frigate
latent latch
#

My assumption is that moving the rigidbody probably takes in consideration of others once you move it. Perhaps something to do with interpolation settings and whatnot.

#

But I'm just kinda throwing out guesses here

#

I just know that rigidbody vs rigidbody calcs require a bit more setup, and it's not as deterministic as saying bouncing a ball across a static environment.

tulip frigate
#

Hm, but i dont think that it still explains why replaying the same record over and over is still deterministic

latent latch
#

True. I'm surprised you do get accurate results by replaying it with that single rigidbody.

tulip frigate
#

After all, the different only lays between whether the player object get the input directly from the input system or from the list

obtuse surge
#

hi guys, so basically im using Animation to move car, does anyone knows why when I play on editor suddenly the object attached got un-attached?

void Start()
{
    animator = GetComponent<Animator>();
}

public void Something()
{
    AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);
    if (stateInfo.normalizedTime >= 1f)
    {
        gameplayTwo.SetActive(false);
        checkpointTele.SetActive(true);
    }
}```
brave musk
#

How accurate is timeline with playing audio clips? I have the playable director on DSP time and have been using the timeline to sequence a rhythm games interactions, but the timing feels slightly inconsistent across plays

#

I'm not sure if there's an issue with the playable director itself, or if it's something with my own code

tulip frigate
fallow quartz
#

Is there anyway to check where a script is being used in unity?

thin aurora
soft shard
thin aurora
thin aurora
#

Otherwise put a log in its awake method like this:

Debug.Log("Awake", gameObject);

You can then press it and navigate to the component

#

There are more ways but these are the easier ones from the top of my head

fallow quartz
#

And is there anyway to check if a method is being used in unity? Like by a keyframe event or in the inspector in a button with onClick

#

or something like that

soft shard
thin aurora
#

It doesn't do that, no

#

Maybe there are extensions like that though

fallow quartz
#

When using SHIFT + F12 on visual studio it doesnt detect StateBehaviourScripts?

slender nymph
#

do unity limit FPS on UI for android build, if yes how can i change the limit

wooden pawn
#

Hello. I am new to using the ScriptableObject behavior for my scripts, but I thought I'd try again by making a set of collectible objects in my game that would go to an inventory system. Right now it's in the early stages, but I ran into an error I'm not sure how to fix:

https://gdl.space/oqafuzamox.cs

When the object is collected, for now I just want it to say in the debug log what item was collected. However, it gives this error:
ArgumentException: GetComponent requires that the requested component 'Weapons' derives from MonoBehaviour or Component or is an interface.
UnityEngine.Component.GetComponent[T] () (at <55fbbbd17b724c15b6abe8c1a3e3289c>:0)
Player.CheckTile (UnityEngine.Vector3 target, UnityEngine.Vector3 raycastStart) (at Assets/Scripts/Player.cs:116)
Player.Update () (at Assets/Scripts/Player.cs:27)

I think I understand what its saying, that the Weapons SO component attached to the game object isnt derived from monobehavior or component, but I have no idea how to change the code or SO so that it works

leaden ice
#

In your screenshot the component is called "Collectible" @wooden pawn

wooden pawn
#

Got it

#

That makes a lot of sense

#

Too many things I'm learning at once

#

My brain starts to combine everything

wooden pawn
#

is this the best way to do it?

#

then I can use Player.collectedItem in the debug log message

wooden pawn
#

public void GetItem()
{
Player p = GameObject.FindWithTag("Player").GetComponent<Player>();
Debug.Log("Attempted to grab item: " + p.collectedItemName + "\n" + "With attached value: " + p.collectedItemValue);

weapons.Add(p.collectedItemName, p.collectedItemValue);

}

Trying to add the key and value to a dictionary called "weapons", but it keeps giving a null reference exception.
The debug log works, saying the items name and value, but it gives an error on the dictionary add line

mellow sigil
#

weapons is null

wooden pawn
# mellow sigil `weapons` is null

public Dictionary<string, float> weaponsDict;
this is at the top of the script(i changed the name to weaponsDict to be more precise)

mellow sigil
#

Yes, that's null. You haven't put anything in the variable

wooden pawn
#

Doesn't the .Add function do that?

#

i must have read the docs wrong

mellow sigil
#

No, that tries to add items into the dictionary but the dictionary itself doesn't exist

#
public Dictionary<string, float> weaponsDict = new();
wooden pawn
#

Oh right I forgot I had to do that

#

Does "new()" work with other things youre initializing, like Vector3s and stuff

#

I've always written it out as = new Dictionary<> etc

mellow sigil
#

You can omit the type in the latest Unity versions, yes

wooden pawn
#

Thank you

harsh rapids
#

Hi everyone, i was updating my project on two different devices, and my player moves at different speeds corresponding to devices, while the values are the same. got any ideas as to why?

#

would it be related to screen resolution?

main shuttle
#

Depends on your movement !code, post it here.

tawny elkBOT
main shuttle
#

My guess is that you don't account for FPS.