#archived-code-general

1 messages Β· Page 128 of 1

earnest gazelle
#

When someone says a texture, it does not imply it is object or asset :/

heady iris
#

fair, I was distinguishing the wrong things there. I should've said that the Texture2DArray object you created is distinct from the asset that gets produced from it.

#

The behavior is certainly a little bit unexpected.

dawn nebula
#

Let's say I expect a value to be within the range of -1 to 1, and I want it where:

  • If it's 0, it's 0.
  • If it's above 0 it's 1.
  • If it's below 0 it's -1.

Any quick math method to get this behavior?

somber nacelle
#

Mathf.Sign

#

ah wait, that returns 1 when it's 0

dawn nebula
#

Odd that the unity one has that behvaiour.

#

0 is not positive unity 😠

swift falcon
#

CS0103

#

what is this error

somber nacelle
#

read the error text

swift falcon
somber nacelle
#

well there you go, you're trying to use something called StartCoroutines but that doesn't exist

#

do you see it underlined in red in your code editor?

swift falcon
#

or visual studio code

somber nacelle
#

then you need to get your !IDE configured

tawny elkBOT
#
πŸ’‘ IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

β€’ Visual Studio (Installed via Unity Hub)
β€’ Visual Studio (Installed manually)

β€’ VS Code*
β€’ JetBrains Rider
β€’ Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

somber nacelle
#

after you complete those steps, spell the method name correctly. it's StartCoroutine

knotty sun
silk cairn
#

what is this person using in order to have 2 values in each item of their list?

knotty sun
silk cairn
#

thank you

#

Im trying that but it doesn't seem to work?

knotty sun
#

because Requrement is not seriazable

silk cairn
#

i just tried that

#

still nothing

knotty sun
#

these classes should not be in the same script file

#

is Item also serializable?

silk cairn
#

no it is not

knotty sun
#

btw a ScriptableObject does not need to be flagged as Serializable

silk cairn
#

okay thank you

knotty sun
#

it you want to serialize Item it needs to be flagged Serializable as well

silk cairn
#

I seperated the scripts, made Requirement serializable and still nothing

#

my item is a scriptable object

knotty sun
#

how are you creating your SO's? I see no CreateAsset Attrbute there

silk cairn
#

the create asset menu is in the Item scriptable Object

knotty sun
#

and for RecipeSO ?

simple egret
#

I don't know if Unity will like constructors on these scripable objects

knotty sun
#

it most definitely will not

#

cannot call a constructor on a Mono or SO class

silk cairn
#

oh it worked

#

I had an error somewhere else so it wasn't loading the saves

knotty sun
#

ffs

silk cairn
#

my bad

knotty sun
#

even so what @simple egret said, you cannot have a custom constructor for Item

topaz sapphire
#

yeah this is come off as stupid

#

if i wanted to replace m1911 with a prefab from a script and keep the same position in the children array as its referenced that way in other scripts

prime sinew
topaz sapphire
prime sinew
#

That's not a question

#

If what you want to know is how to set the child position in the Hierarchy, then Google "how to change position of child in hierarchy unity"

potent sleet
latent latch
#

removing contents does not remove the index of the array if that's what you're asking

topaz sapphire
latent latch
#

as long as you use the same index

prime sinew
potent sleet
prime sinew
#

It's not the order in an array, it's the one in the Hierarchy

latent latch
#

Ah, right yeah that's a little different

latent latch
#

if you did GetComponents it would just give a temp array basically of the references

prime sinew
#

Don't know if you're having trouble with the spawning, replacing, or ordering of the child because up till now you haven't actually asked a question

prime sinew
#

Where?

#

I don't know why you want to argue instead of clarifying

topaz sapphire
#

"if i wanted to replace m1911 with a prefab from a script and keep the same position in the children array as its referenced that way in other scripts"

#

do i NEED to put a question mark after?

prime sinew
prime sinew
#

Do you know how to spawn an object?

topaz sapphire
prime sinew
#

Forget this

#

<@&502884371011731486>

topaz sapphire
#

keep making remarks then

#

@latent latch can you give me a hint?

#

you seem to know what your doing

quartz folio
# topaz sapphire keep making remarks then

They don't know what part of it you don't know how to do, and these are the questions you should be answering:

Don't know if you're having trouble with the spawning, replacing, or ordering of the child

quartz folio
#

What do you know how to do out of the question you asked, because there's multiple steps, just destroy the object, spawn it, then change the sibling index using the transform APIs

latent latch
#

There's a bunch of methods relating to shifting placement in the hiearchy that may be what you're looking for

topaz sapphire
latent latch
#

Yeah, you can just assign the sibling index if it's in the correct transform list

#

otherwise just move it to the first index if you're using 0

topaz sapphire
#

so delete, instantiate, update index

latent latch
#

Sounds about right

#

instantiate with the same parent as the previous prefab

topaz sapphire
#

done

#

watch this not work

#

it didnt work

somber nacelle
#

in what way did that not work?

latent latch
#

that text 0_0

somber nacelle
#

yeah that font is a war crime

sleek hedge
#

is that terraria

topaz sapphire
#

i wanted to change the windows desktop font

#

changed everything on accident

potent sleet
#

not as bad as comic sans

topaz sapphire
#

even the activate windows is corrupted

lean sail
#

this just gets more and more chaotic

#

id believe u if u said u were coding this on a samsung fridge at this point

topaz sapphire
#

it worked

pale spindle
#

Good evening friends.

#

I need to fire a sound via a audio clip. I have AudioSource and AudioClip in a empty child object called Audio Manager

#

But in my PlayerController, how do I access the clip from the other script?

somber nacelle
pale spindle
#

ok πŸ™‚

#

this is my AudioController.cs in Audio Manager gameoject

#

using UnityEngine;

public class AudioController : MonoBehaviour
{

public AudioSource source;
public AudioClip torpedoFired;

}

#

this part is fine right?

#

i linked it in the editor too

somber nacelle
#

sure

pale spindle
#

ok

somber nacelle
pale spindle
#

video is better, adhd likes video

#

@somber nacelle not sure yet :/

#

where would you put your audio?

#

its a simple copyright clone of space invaders but my spin on it

#

for fun, not release/sell

#

all 2d

#

i subbedy to you too πŸ™‚

prime sinew
topaz sapphire
pale spindle
#

void PlayTorpedoSound()
{
audioManager.GetComponent<AudioSource>().clip = false;
}

#

well this is a fail

somber nacelle
#

that line doesn't make any sense

pale spindle
#

i got the first part right but not sure what to do at the end of ().

#

public class PlayerController : MonoBehaviour
{

[SerializeField] private GameObject audioManager;
somber nacelle
#

if you want to put nothing in the clip property then assign null because it's not a bool

pale spindle
#

ok

somber nacelle
#

but also, just reference the AudioSource directly, you don't need to reference the GameObject just to then call GetComponent on it

pale spindle
#

how do i do it direct then?

#

everything is different now in 2023, last time i did a clip was 2015

#

XD

quartz folio
#

Reasons to not make video tutorials: they're hard to update πŸ˜„

pale spindle
#

Unity Learn sucks as bad

somber nacelle
pale spindle
#

some of the stuff they have you do is missing/moved

quartz folio
pale spindle
#

i got the reference part but this is losing me

#
   void PlayTorpedoSound()
    {
        audioManager.GetComponent<AudioSource>().
    }
#

what goes at the end of .

quartz folio
#

You don't need to use GetComponent if you have referenced the component directly

pale spindle
#

ok

quartz folio
#

Do you have proper autocomplete and error highlighting in your IDE?

#

because you should be able to just see the members and access them easily as you type

pale spindle
#

yes but grr 😦

#

hes using PlayOneShot

#

I dont see that :/

#

even with the reference

quartz folio
#

Your audio manager is not an audio source though

#

it contains the variable that you need to reference first

pale spindle
#

ok :/

somber nacelle
# pale spindle

you changed the variable type so you have to drag the object in again because it was previously serialized as a GameObject type

pale spindle
#

ok got it

#

[SerializeField] private AudioClip torpedoFired;

#

also dragged the CLIP in

#

but where is playoneshot?

potent sleet
somber nacelle
#

that's the AudioClip not the AudioSource

pale spindle
#

im doing a clip not music :/

#

oh, sec

potent sleet
#

AudioSource is like your radio

pale spindle
#

so do i want a clip or a source?

potent sleet
#

audioclip is the casette

pale spindle
#

i wish they would make 1 for all

#

ok

somber nacelle
pale spindle
#

void PlayTorpedoSound()
{
audioSource.PlayOneShot(torpedoFired);
}

#

we good i think ,testing

#

BINGO

#

ok it worked πŸ™‚

#

So whats the best strategy for managing audio and clips in the future?

potent sleet
#

sound manager

pale spindle
#

as a empty game object? that's what i got now

#

i think its redundant

potent sleet
#

I would name the gameobject the same name of the script

pale spindle
#

fair enough, done

potent sleet
pale spindle
#

why does things get more complex? soon unity is gonna demand 50,000 javascript libs :/

#

but i will check it out

potent sleet
#

javascript ?

pale spindle
#

was a joke since js is horrible in webdev

#

anyway reading, min

#

public class Singleton : MonoBehaviour
{
public static Singleton Instance { get; private set; }
}

#

So would this be in its own script in an empty object?

potent sleet
#

did you kinda just skim through the article ?

pale spindle
#

im trying to see if i need a gameobject, sec

potent sleet
#

any monobehaviors needs a gameobject .
doesn't need to be called Singleton though

pale spindle
#

Yes, jsutneed a empty, name it Audio Controller as my script is named. and add a class with just the singleton to it

#

and call the singleton anywhere i need it for audio in my other source code

grand trench
#

I followed this tutorial while trying to make a state machine to go ahead and add the movement to the player
https://www.youtube.com/watch?v=K1xZ-rycYY8&ab_channel=bendux
However, when I moved, I wouldn't stop moving when i let go of the key. To fix this for moving left and right, I added the line rb.velocity = new Vector2(0,rb.velocity.y); to my idle state, which stops the player when the state is idle. However, for jumping i'm not sure what to do. When i press space, the player just flies upwards at a steady pace and never falls back down. I'm very confused. Here is my script in the player (a lot of stuff in here isnt finished yet)

potent sleet
pale spindle
#

i will try harder

potent sleet
#

nothin to be sorry about just read the pros and cons lol

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

potent sleet
#

@grand trench

#

you should be doing the jump the same way the tutorial you're following is doing.

grand trench
#

Is it not the same?

potent sleet
#

you haven't posted the code correctly

#

did you read the bot msg?

grand trench
#

Yeah just give me a minute

pale spindle
#

@potent sleet

#

not gonna lie

#
    void PlayTorpedoSound()
    {
        Singleton.Instance.AudioController.audioSource.PlayOneShot(torpedoFired);
    }
#

looks way better and easier to access

potent sleet
pale spindle
#

.... ok now what???

potent sleet
#

make methods

pale spindle
#

that is a method

potent sleet
#

not everything should be public

pale spindle
#

its called void PlayTorpedoSound()

potent sleet
#

you're getting the audioSource

#

and playing OneShot

pale spindle
#

yes

potent sleet
#

don't do that

pale spindle
#
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{

    public AudioClip torpedoFired;

    public Rigidbody2D rb;
    public GameObject torpedo;

    private float horizontal;

    [SerializeField]
    private float playerSpeed = 4f;

    public void OnMove(InputAction.CallbackContext context)
    {
        horizontal = context.ReadValue<Vector2>().x;
        rb.velocity = new Vector2(horizontal * playerSpeed, rb.velocity.y);
    }

    public static GameObject Create(GameObject prefab)
    {
        return Instantiate(prefab);
    }
    public void FireTorpedo(InputAction.CallbackContext context)
    {
        if (context.performed)
        {
            Debug.Log("Played sound!");
            PlayTorpedoSound();
        }
    }

    void PlayTorpedoSound()
    {
        Singleton.Instance.AudioController.audioSource.PlayOneShot(torpedoFired);
    }
}
#

this is the playercontroller.cs

#

so how do i do the "method" way now?

potent sleet
#

Singleton.Instance.AudioController.PlaySound(torpedoFired);

pale spindle
#

there is no PlaySound

potent sleet
#

smh

pale spindle
#

Singleton.cs

potent sleet
#

you make the method inside the audiocontroller

pale spindle
#
using UnityEngine;

public class Singleton : MonoBehaviour
{
    public static Singleton Instance { get; private set; }
    public AudioController AudioController { get; private set; }
    public UIController UIController { get; private set; }
}

#

which method?

#

PlaySound()?

#

ok

potent sleet
#

you're trying to run before knowing to walk

pale spindle
#

yes im 44 and have no life

#

i need to do something before i lose my mind :/

potent sleet
#

just my 2c : don't have to rush through it and take the time to learn the basics before mashing random code together

#

also your singleton class is missing the assignment

#

you're gonna get a NullRefException if you tried running it

pale spindle
#
using UnityEngine;

public class AudioController : MonoBehaviour
{

    public AudioSource audioSource;
    public static AudioClip torpedoFired;

    public static void PlayTorpedoSound()
    {
        audioSource.PlayOneShot(torpedoFired);
    }
}
potent sleet
#

Instance = null

pale spindle
#

😐

#

ok

#

adding it now

potent sleet
#

are you troling or

pale spindle
#

NO

potent sleet
#

why is this static
public static AudioClip
public static void PlayTorpedoSound

pale spindle
#

I said im adding the damn code check now for instance

#

because it's what I use in C# to access certain methods

#

I willr emove it

potent sleet
#

defeats the whole point of doing a singleton instance

#

also you cant assign static fields in inspector

pale spindle
#

ok, noted

#

mono is def different from full blown c#

#

i gotta get used to it heh

potent sleet
#

you wouldn't use static everywhere in regular .NET either

#

also unity is "full blown c#" just up to 9

#

there are specific things related to inspector and API unity only

pale spindle
#

basically what you had

#

and audiocontroller.cs

#

look fine now? :/

potent sleet
#

wtf are u doing mate

#

like seriously

pale spindle
#

oh ffs

potent sleet
#

where in the article is this the same ? btw

pale spindle
potent sleet
#

dawg, you put Destroy(Instance)

#

big difference

pale spindle
#

oops :/

#

tired 😦

potent sleet
#

perhaps take a break

pale spindle
#

I don't get time to 'code' this is my time :/

#

11:12pm

#

else i could stop sleeping and just use those hours, i work full time in a deli :X

grand trench
#

my bad for taking long i had to use bathroom

potent sleet
#

coding tired will just lead you to make dum mistakes like switching audiosource to static field and then trying to new () it πŸ€” @pale spindle

pale spindle
#

fine :/

#
public class AudioController : MonoBehaviour
{

    public AudioSource audioSource;
    public static AudioClip torpedoFired;

    public void PlayTorpedoSound()
    {
        audioSource.PlayOneShot(torpedoFired);
    }
}
#

there nicer

#

i should now take a break

#

playercontroller:

#
    public void FireTorpedo(InputAction.CallbackContext context)
    {
        if (context.performed)
        {
            Debug.Log("Played sound!");
            Singleton.Instance.AudioController.PlayTorpedoSound();
        }
    }
potent sleet
#

TorpedoFired shold not be static...

#

why is is it still static

pale spindle
#

removed static , i forgot to there

potent sleet
pale spindle
#

its a older line, fixed

#

no more statics, im not using em anymore for this kind of stuff then

potent sleet
#

try to keep static for helper methods in POCO classes

#

or Instances/Singleton

pale spindle
#

fair enough

#

i will get used to this new way, old habits i tried w/o any singletons/instances for audio

grand trench
pale spindle
#

now im finding it out the right away, gonna reread your article and also @somber nacelle and @quartz folio

grand trench
#

but its the same way he did it

pale spindle
#

just to be sure πŸ˜„

grand trench
#

as far as i know

#

i meant within a method*

#

the jump functionality happens within fixedupdate, and uses the same line he uses

#

yet it works differently, why?

potent sleet
pale spindle
#

I'm gonna chill and work on things when my head is clear, im off this weekend so it helps

#

Else all I'll do is spin my tires and burnout. πŸ˜‚

potent sleet
pale spindle
#

I do like this singleton approach tbh πŸ™‚

grand trench
pale spindle
#

Thanks for slapping some sense into me @potent sleet

grand trench
#

wwhich is the same thing my movement did but as i said in my original explanation, that was easy to fix

potent sleet
pale spindle
#

Gonna netflix and chill and sleep.

pale spindle
#

Ok, time to unplug my brain and watch something and go to sleep.

potent sleet
pale spindle
#

Thanks again

buoyant crane
grand trench
#

ah

potent sleet
#

yup and video puts it inside a key

buoyant crane
#

technically it’s the same line, but the difference is his is being called once

#

and yours is being called every fixed frame as long as the state is Jump

potent sleet
#

++ "Followed exactly like tutorial, they did not"

grand trench
#

null

buoyant crane
grand trench
#

omg

#

i just put the code in different places without thinking but i still followed how the tutorial made it

pale spindle
#

you pulled a core πŸ˜›

#

gg tho for seeing it tho

#

night all πŸ™‚

grand trench
#

what are you showing me

potent sleet
#

the video you said you did exactly like u did

grand trench
#

as i said i used the same line he did i just put it in the wrong place

potent sleet
#

thats why copying blindly without knowing why its where it is is generally a bad idea πŸ˜›

void basalt
#

^

grand trench
#

null shut up

potent sleet
#

its ok maybe next time you won't do it again

grand trench
#

i didnt copy it blindly asshole

pale spindle
#

chill dimrod

grand trench
#

i was thinking about what i was doing i just thought wrong

void basalt
potent sleet
grand trench
#

i made the wrong decision, not like i turned my brain off and just threw some code down

pale spindle
#

thanks again @potent sleet @quartz folio and @somber nacelle ❀️

#

gonna go sleep and play with stuff tomorrow again

#

have a good one

#

i got inputs to work so im happy too πŸ˜„

potent sleet
grand trench
#

i actually didnt need to change where it was after all i just had to add an extra check to make sure you're grounded

#

so my thinking wasn't even entirely wrong

#

i just forgot one part

carmine orbit
#

I am trying to set a boolean array by accessing an equal part of another Gameobject array which works but the problem is that the GameObject array auto populates the array but the player states will not and it makes me auto increase the length in the inspector does anybody know why?
https://gdl.space/ayimulagor.cpp

swift falcon
#

is there any way to use game objects or prefabs as a class

#

so like if i have a game object cheese cake

#

i want to get information about it's transform, rigibody etc in a script

void basalt
#

Each script you put on an object, is a class.

swift falcon
#

right

void basalt
#

if your cheese cake object has a CheeseCake class, then yeah

#

I guess thats doing what you want

swift falcon
#

i guess what i'm thinking is

#

if i need to add or remove components at some point

#

i don't want to manually have to go change my CheeseCake class each time to reflect that

#

but i guess it's not a big deal

void basalt
#

For example, if you wanted to pick up the cheese cake as an inventory item, or eat it as some generic food item, you would use interfaces

#

Idk if that answers your question

swift falcon
#

interfaces are new tech for me so i guess i'll find out

void basalt
#

You can always create a base Food class

#

and then derive cheesecake from it

#

I'm not sure what you mean by add or remove components though.

#

If you change from a rigidbody to a character controller, then yeah you'll have to go in and edit the code

swift falcon
#

i guess if you wanted information about its position, you'd have to get its transform, but if you wanted its colour then you'd have to ask its material or w/e

fervent furnace
#

@carmine orbit the findobjectswithtag each time returning a new array…

swift falcon
#

and even if you just made a cheesecake class, you'd have to assign all of its values individually right ?

void basalt
#

I mean, you could create variables. In Start(), you set each variable to the component you just searched for

#

then you just use the variables

swift falcon
#

like there's no "get all components attached to this game object" function or anything i guess is really what i'm asking

void basalt
#

No, because that wouldn't make sense

swift falcon
#

gotchu

void basalt
#

You could rig something up

#

that like, automates it

#

but no, theres nothing like that by default

swift falcon
#

ty

rugged spear
#

I need some advice. For my player movement script, what would you guys say is "best practice" to put all input detection and CharacterController.Move/other movement code all inside the Update method? Should I instead move all of the logic (including input) to FixedUpdate? Or should I use Update to store inputs as variable(s), and let FixedUpdate apply movement based off the stored variables?

void basalt
fervent furnace
#

You can try gatcomponents<component> but ihavent try it before so i am not guarantee it will work, even if it works you will get a bunch of components that you dont know what they are

void basalt
#

fixedupdate ticks at a fixed rate. Default is 50hz

#

you don't want to increase that rate especially if you're screwing with physics

#

The professional AAA way to do it, would be to run all simulation logic at fixed rate, and interpolate visual renders on frame updates

#

if you're just beginning, you probably don't want to do that

rugged spear
#

why can't you just do something like Mathf.Lerp(something, something, something * Time.fixedDeltaTime) in fixed update?

void basalt
#

Because that's not how you lerp

#

If you're really curious, I could show you how to do it properly

buoyant crane
# swift falcon like there's no "get all components attached to this game object" function or an...

if there is, it won’t be as useful as you think it would be.
If you grab your CheeseCake GameObject and you know it already has a rigidbody using .rigidbody (doesn’t exist), it’s essentially the same as .GetComponent<Rigidbody>(). It would be a bit practical since less typing i guess, but not possible in c# without being extremely painful πŸ™ˆ.
Likewise, if you wanted a collection of all components (rb, renderers, custom scripts) on the game object, that’s also possible using GetComponents<Component>() similar to what was said above me

rugged spear
void basalt
#

standby

#

writing you some code

rugged spear
#

understood, thanks in advance

void basalt
# rugged spear understood, thanks in advance
float tickDelta = 1 / tickRate; // Time between each tick
float timeAccumulator;

void Update() {

timeAccumulator += Time.deltaTime;

while (timeAccumulator >= tickDelta) {
timeAccumulator -= tickDelta;
CustomFixedUpdate();
}

float interpolationAlpha = timeAccumulator / tickDelta;
Vector3.Lerp(myObjectPosLastSimulation, myObjectPosCurrentSimulation, interpolationAlpha);

}


void CustomFixedUpdate() {

myObject.Move()...

}```
#

I wrote this in notepad. Some stuff might be wrong, but the idea is correct

#

you cant use unity's fixedupdate

#

you have to make your own clock

rugged spear
#

interesting

void basalt
#

otherwise you can't access the interpolator alpha

#

this is how it's done in multiplayer games

rugged spear
#

right, because Time.fixedDeltaTime is always 50hz (0.02)

#

I was wondering about that

void basalt
#

yeah, you wouldn't use fixedDeltaTime

#

just regular deltaTime

#

all we're doing is accumulating time to figure out when the next tick should be

rugged spear
#

i see

#

I'm assuming tickRate would ideally still want to be 50 to be as close to the normal fixed timestep?

#

Or it could be faster if I understand correctly

void basalt
#

cod warzone uses 10hz tickrate

#

it can be anything

#

lower it is, better performance you'll get

#

but less responsive

rugged spear
#

because Update (on most new systems) will be called much faster than 50hz

void basalt
#

Correct. Calling character controller updates or doing anything intensive in Update() is a massive waste

rugged spear
#

I see. This is a great point that I never even thought to consider until now

#

Thank you for this

#

So in theory FixedUpdate would only be useful for stuff involving custom physics?

void basalt
#

You can run any custom physics code in the CustomFixedUpdate I showed you above

#

That's really all unity's FixedUpdate is doing

#

there's nothing magic about it

#

but

#

you'll need to manually tick the physics engine

rugged spear
#

I'm just wondering what FixedUpdate is useful for then

void basalt
#

physics code has to be called on a fixed basis

#

it shouldn't run in frame updates

rugged spear
void basalt
#

It can be a character controller, or rigidbody velocity sets, add force, etc

#

You'll need to disable automatic physics updates

#

and run this at the end of the while loop

#

Generally we call it a "Simulation Loop"

#

all simulation data should run on a fixed basis

#

so like shooting guns, moving, etc

swift falcon
rugged spear
#

So why is CustomFixedUpdate invoked in the Update method? What if the frame update stalls for a while (lets say 1 whole second for some reason)

void basalt
#

especially when you're only running a map with 8 players with raycast guns

#

and nothing else

swift falcon
#

true

void basalt
#

the while loop catches up in case your game locks up

#

so yeah, you could have 2 simulation steps running in the same render frame

#

not uncommon

rugged spear
#

Ah yes good point, I didn't realize that

#

I see now

#

Sorry for my ignorance lol

#

Thank you for the explanation

void basalt
#

You're getting it better than most people

#

If you put it inside VS and format it correctly, you'll be able to read it a lot better

rugged spear
#

If I'm being honest this seems like a game-changer (literally) πŸ˜„

void basalt
#

ECS is the real game changer if you're looking for raw performance

rugged spear
void basalt
rugged spear
#

So I would have to implement your example in every script that needs some type of physics step?

void basalt
#

You would generally write your own entity system

#

any object you instantiate, you would do it through the custom entity system

rugged spear
#

I see

void basalt
#

thinks like player rotations should also be handled in Update()

#

otherwise you'll get nasty input lag

#

As for the entity system, you could just create a new base class called SimulationEntity, or whatever you want

rugged spear
#

So I'm thinking I would make a system that's higher up in the script execution order that can register some type of "callback"

void basalt
#

then have all of your new scripts derive from that

#

yes, the class system ^ would handle that

rugged spear
#

I see

void basalt
#

On the base entity class, you would have SimulationUpdate()

#

then you can call it on any entity that derives from it

#

etc

rugged spear
#

right, gotcha

#

interesting

#

thank you for the pointers

carmine orbit
rugged spear
void basalt
rugged spear
#

ah okay

void basalt
#

that's why it's not logical for most games to just "up the tickrate" because then you run into bandwidth issues

rugged spear
#

yeah that makes sense

rose stream
#

can I ask some C++ related help here

#

its a simple question with which I am struggling

void basalt
#

@rose streamIf it's unity related, I don't see why not

rose stream
void basalt
#

fire away

gleaming burrow
#

Heyy, First time asking for help here, so I hope this is the place to do it. >~<
I'm using a script to spawn random humans, with random meshes and texture. I was able to get the meshes working, but swapping the textures has proven to be a little more difficult.

From what I can tell the correct texture is being applied to the component as a instance ; what I want. But the original material is still there and appears to be overriding the instance texture.

public SkinnedMeshRenderer class1
public Texture Farmer1;
public int skinPicker;

skinPicker = Random.Range(1, 4);

if (skinPicker == 1)
{
class1.material.SetTexture("_MainTex", Farmer1);
print("Skin 1 Applied");

        }

Any help would be amazing, i've been looking online for the past 2 hours and I cant work it out.

leaden ice
rose stream
leaden ice
#

also why did you name your renderer "class1"

rose stream
#

i think copy paste stuff happening there

gleaming burrow
leaden ice
#

No idea why you're adding a second one

#

You have to show your code

#

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

leaden ice
#

Open the materials dropdown that's the only important bit here and you have it hidden

rose stream
#

ok i have a question
in C objective you have a statement like char** argv
in which you give pointer to a pointer of a char
like char[][]
or like string[]
would this work in C++
where char** dont work as expected
they simple use char* and assign the value
or sometimes char* argv[]

#

also if its a char** argv
how can I call it in C#

void basalt
#

First of all. Do you really need to go into native?

#

Because it complicates things 100%

#

You can use pointers in C# if thats what you're after

rugged spear
#

char* argv[] is just an array of pointers, and so is char** essentially

rose stream
#

so gotta make use of C++ as C# bitfields are not supported

rose stream
#

if they are then I did have to make use of enums and that is a pretty pain

rugged spear
#

iirc char** can be marshalled as new char[] { 'a', 'b', 'c' }

rose stream
void basalt
#

you would use the byte type

rose stream
#

i once used a marshal where I gave only string [] as input and it worked

#

but forgot how?

void basalt
#

chars are two different sizes between C++ and C#

#

byte**

rugged spear
#

actually yeah that's correct, definitely use the byte type (in c#)

void basalt
#

you'll need to enable unsafe code

#

and mark the functions as unsafe

rose stream
swift falcon
#

is there an easy way to make a list "readonly", like anything can see the list and its contents, but are unable to use List.Add() and other methods like that ?

rugged spear
void basalt
#

yeah chars in c# are 2 bytes

rugged spear
#

Yeah don't confuse c++ char with c# char

rose stream
void basalt
#

right

#

so use the byte type in c#

lean sail
rose stream
#

like unsigned int i : 3;

void basalt
#

bit shifting

rose stream
#

better let me be my way

#

anyways thx for the help

rugged spear
rose stream
#

pretty dirty implemented but works the best for me

#

also wouldnt
fprintf(stderr, "Error: could not open input file\n");

#

cause unity to crash?

void basalt
#

invalid memory accesses will cause unity to silently crash

rose stream
#

now i get it why unity crashed last time

#

i thought fprintf is present everywhere
so it wouldnt crash

#

would this work in android
FILE* infile = fopen(argv[1], "rb");

rugged spear
rose stream
rugged spear
rose stream
#

i need decoder

rose stream
#

with crc32 packets
and raw vorbis packets
header sizes and linked lists
those decoders simply dont reveal that much

void basalt
#

Why do you need this exact format?

rose stream
#

to create a replica of fsb5 format
like you know
FSBank is supported for windows only
i am trying to write something that replicates it
FMOD Studio only takes input of fsb4 and fsb5 files
in unity fsb5 is the output of every audio file
with compression format vorbis
as vorbis is kindda used everywhere
so anyone can dynamically make a load of .ogg or .wav file and convert it to .fsb5
then make use of it in Fmod studio

#

my goal is android,linux and mac

rugged spear
#

If you want to write your own C# bindings for the library, you'll have to first build the C++ library for your target architecture (for example android could be maybe AArch64/ARM64)

rose stream
#

already did

#

for ARM32

rugged spear
#

And you're using the correct native library for your testing?

rose stream
#

yep

#

ogg and vorbis static android libraries compiled with android studio using jni

#

not done by me
found on github

rugged spear
#

Have you thought about writing a test app (in C#) before messing with it in Unity?

rose stream
#

but I am going to try it again one more time

rugged spear
#

Actually can you post a pic of the inspector for the native lib?

#

in unity

rose stream
#

for both android and pc

#

then you can have a look

rugged spear
#

im more concerned about the import settings or whatever it's called

rose stream
#

make sure its in different folders and architecture type is defined otherwise unity wont build and generate an error with 2 libraries with same name

rugged spear
rose stream
#

gimme 30 minutes so I can finalize things

rugged spear
#

okay so try debugging by another means. don't print to stderr (maybe stdout) or simply just write to a file using something like std::ofstream

#

Wait how are you invoking the method in c# first of all

rose stream
rose stream
soft shard
#

Im looking over some of Unity's code for the "new" input system rebinds, they have var partName = default(string);, I understand default(T) is useful when you dont know what default value T might accept (for example, you cant make a int null, or set an Object/class to 0), though is there maybe a micro-performance reason why Unity would choose to use default(string) specifically instead of string.Empty or just "", or is it just a convention/good practice?

rose stream
#

that,s why you cant

fervent furnace
#

@carmine orbit was there anyone answer you yet? I will not call findobjectsss in every update, if the number of gameobjects is static i will call it in awake or start only else i will consider object pool

soft shard
# rose stream object/class is 0 the memory is managed by the CLI

Well I understand why you cant set a class to 0, cause its not a numeric type, I was more wondering why Unity would choose to use default(string) instead of string.Empty or just "", since in this case "T" is string, and I dont see a reason why someone might want to default a string in this way as oppose to the others

rose stream
#

from 0 i meant total null

#

NULL

#

0

fervent furnace
#

0 mans nothing is allocated

rugged spear
#

The reason you can't set int to null is because it's a struct, and structs are value-types which apparently can't be null

void basalt
#

correct

rose stream
#

yep

fervent furnace
#

Null string means you have to allocate a char* for one byte and remember its capacity and size

rose stream
soft shard
#

So default(string) allocates nothing, and string.Empty and "" would allocate 1 char*?

rose stream
#

remember CLI

#

in C# the memory is managed by the CLI

rugged spear
#

To answer your question I don't think you need to worry about performance in this case

soft shard
fervent furnace
#

Oh i forgot string in c# is immutable so you probably need a char* and size only

rose stream
#

you just cant do a string null

#

but yeah
you can do the null to a pointer as the size of the pointer or stacks is not defined

rugged spear
#

In C# you can set a string to null, because it's a class (reference type)

rose stream
#

wait
what?

#

then I am forgetting something

#

fuck i am out

soft shard
#

O.o

rugged spear
#

It's basically saying this reference points to nothing. The same as nullptr in cpp iirc

rose stream
#

its eating brain now

rugged spear
#

"" != null

#

it's just empty

fervent furnace
#

β€œβ€ is Equivalent to a ptr[0]=0 you need a byte to store this β€œ0”

soft shard
#

Ah ok, I think I understand what you mean now, that convo did help after re-reading it a few times, thanks - it was some Unity code I saw im using as reference for rebinding, so was just curios, though a single byte doesnt sound like something worth micro-optimizing in production anyway

dawn nebula
#

How often do you guys used UnityEvents? I use them pretty prolifically to bind my prefabs together.

rose stream
#

memory is something that takes months to understand
took me 6 months to understand how computer memory worked

rose stream
rugged spear
dawn nebula
rose stream
#

i still remember it

soft shard
rose stream
#

is armaebiv7a simply ARM32

rugged spear
rose stream
#

?

rugged spear
rose stream
dawn nebula
#

Memory should always be in mind.

rugged spear
#

it doesn't "just collect garbage" it also moves memory around at will whenever it wants to

#

oh okay sorry πŸ˜„

rugged spear
rose stream
#

lol

dawn nebula
#

yep

rose stream
#

it did be a pity if someone can tell me is armaebiv7a simply arm32 or arm64

dawn nebula
#

How often do you guys use UnityEvents? I use them pretty prolifically to bind my prefabs together.

dawn nebula
#

_>

rose stream
#

anyone guess my age?

rugged spear
#

To me UnityEvents are just a cool way for Unity to serialize traditional c# events but I don't use them very often

soft shard
rugged spear
lean sail
#

I dont see why you would really use it to bind prefabs, I just use it for stuff thats supposed to happen in scene. Like a pressure plate triggering a specific door = unity event. That way I can visually know which door i am selecting

#

Doing it through regular c# events is kinda weird imo

rugged spear
#

Yeah I think in terms of performance/usability it's more of a visual thing(able to be serialized in the inspector I believe) but it's essentially the same concept as regular c# events

#

maybe I'm thinking about UnityAction actually, I think that's literally the same as System.Action

soft shard
#

I do find it a little odd that typically youd create a empty UnityEvent class so it can be serialized, and just an empty class in the project seems like a weird concept to me

lean sail
#

πŸ€·β€β™‚οΈ sometimes things just need to be setup in scene

lean sail
#

its weirder to have my door for example, know about which pressure plate its trying to react to. Or weird to have another system entirely hook things up

dawn nebula
#

if you do something like public UnityEvent gameEvent in a monobehaviour it'll appear in the inspector automatically

soft shard
lean sail
#

I dont really know what the empty class thing meant either now that i read this

rugged spear
#

I feel like it's a more streamlined SendMessage feature with some added benefits

#

and drawbacks i think

lean sail
#

i still dont get the point of using it to bind prefabs, but it definitely has its uses otherwise

rugged spear
#

it definitely has its uses yeah, probably just a preference type of thing

dawn nebula
#

from the inspector

#

It gives you the same functionality you see with Unity's button or toggle component.

#

or those TextMeshPro unity events

rugged spear
#

or regular c# events, just with the added bonus of being able to manipulate it in the inspector

dawn nebula
#

yes

#

but that's BIG

rugged spear
#

true

#

it's probably just that they had to make their own custom implementation to add some magic "under the hood" to be able to serialize everything properly in the inspector

dawn nebula
#

Separate question.

#

Imagine you had collectable drops.

#

Like money or items or whatever.

#

Let's say you sort of expect a lot of them on the screen at once.

#

And when the player gets close, the collectable flies over to them.

#

Would you give the player some trigger collider that interacts with collectables and tells them to fly to them.

#

Or would you give each collectable a trigger that waits for the player.

lean sail
#

if only the player can pick them up, id go with it maybe on the player

#

thats a lot less trigger colliders

dawn nebula
#

ya the logic is... having it on the player gives less control, but is more performant

lean sail
#

there becomes a point where writing scalable systems is just not worth it

#

you could make every system as scalable, adjustable, whateverable as possible. But if you wont ever expand on it then no point worrying about it

#

you could give that same trigger and script to anything else that can pickup items too

rugged spear
#

wouldn't you still need to give each collectable a collider(trigger) so that the player trigger can detect if it's intersecting with a collectable? or am i misunderstanding

dawn nebula
#

well the collectables need a normal collider so they dont fall through the floor and shit

rugged spear
#

oh yeah true πŸ˜†

lean sail
#

thats what i was assuming too, i imagine there wouldnt be a massive performance hit anywyas unless you have a ton of items on the floor

#

but at that point, the amount of game objects would be worse than the trigger lol

rugged spear
#

I think the logical solution would be to have a single trigger on the player then because otherwise you'd need a collider for actual physics collisions and then wouldn't you need a second one (per collectable) that's a trigger? I forget if triggers still have normal collisions or not 😭

lean sail
#

Yes u would need both

#

The only scenario I can think of for putting the trigger on the object would be if the object is unique, or interacts with anything/anyone.
You wouldnt want your player to have a trigger for items, then another for idk opening a door when you are close

#

Which is a lot of scenarios I guess, idk why I said only

#

For example I have a cube which dissolves when the player comes close, it has a trigger on the cube itself. No need for the player to do this behaviour, so the script is on the cube

rugged spear
#

so wouldn't having both a normal collider and a trigger collider on each collectable item be like O(n) more expensive?

lean sail
#

Calling it O(n) sounds weird for number of triggers but yes. Which is why I agree to put it on the player in this case

dawn nebula
#

I mean if the player is chilling on its own physics layer and you just have a bunch of triggers listening for that one collider, it's pretty whatever.

#

Cost wise.

rugged spear
lean sail
# dawn nebula I mean if the player is chilling on its own physics layer and you just have a bu...

If it's one object it doesnt matter what you put it on, but depending on the use case sometimes it makes more sense for it to be on the object or player.
Like a ship opens up when you come near, put it on the ship. Even if theres multiple ships at least they can have their own events and whatnot
You pickup an object by being near, put it on the player. But in this case theres obviously multiple objects.

#

Even tho both are essentially the same, check if the player is within range

rugged spear
#

You could theoretically use Physics.SphereCast too but I'm not sure how expensive that is, maybe less such if you're only targetting specific layers but I can only assume it's fairly high compared to having the physics system detect intersections with triggers

lean sail
#

Every object on the floor too will basically have the same behaviour. If you want different behaviour it can just inherit from IPickupable (idk maybe name it better) and define it's own implementation

rose stream
#

my gradle build failed

#

any helps?

ashen yoke
rose stream
#

it says 'android.enableR8=false' is deprecated.

#

i had this error before as well
like a year ago
now i forgot how to fix it

#

any helps

rugged spear
#

You'd only need 1 collider per collectable

dawn nebula
#

To give a better idea for the pickup I'm imagining. Think of the XP bits from those Vampire Survivor games.

#

Lots of them.

#

These blue crystal thingies.

ashen yoke
#

if you have a choice between maintaining giant amount of in scene colliders, triggers whatever and a simple straight forward solution out of scene graph that is slightly more expensive, chose the latter

#

treat performance costs as balancing act, is it reasonable to exchange performance for clean architecture?

rugged spear
#

My opinion: fuck around and find out πŸ˜„

dawn nebula
#

Step 1) Fuck Around
Step 2) Find Out

ashen yoke
#

because if you rely on physics for that, youd end up with large amounts of game objects in the graph just to have colliders

#

that cost can be alleviated with some simple spatial structure, probably

#

so you dont have to have gameobjects

rugged spear
#

AABB isn't terribly expensive either if that's a possibility

ashen yoke
#

still need spatial acceleration to narrow down

#

a simple grid would do miracles there

rugged spear
#

definitely with that amount of objects

ashen yoke
#

spatial hash would work with maps of any size

rugged spear
#

especially since they seem to be clustered together so tightly

dawn nebula
#

I doubt those games have insane optimizations beyond pooling

#

but maybe im wrong

ashen yoke
#

afaik its not made in unity

#

so it by default doesnt have associated gameobject/scene graph overhead

#

but it 100% has acceleration structure

#

there is no way around it

lean sail
#

you would probably need ecs tho for the amount of enemies it has

dawn nebula
rugged spear
#

I'm under the impression that ECS could be "the way" to do such a thing, but you could theoretically get by (probably fairly well) with the various techniques mentioned above

ashen yoke
lean sail
#

actually idk how many enemies it has, ive only seen gameplay briefly where the screen was full

rugged spear
#

I've never seen the game, but I've seen some very impressive 3d work with ECS so I can only guess

ashen yoke
#

ecs is certainly good pick here, unity one will provide massive performance gains, but if you dont need it, like in case of vampires you can get away by simply looping a list of objects

#

there arent that much objects, and just looping them will work just fine

#

they also dont have any advanced ai

#

so you dont maintain 1000 bts

dawn nebula
#

Ai is literally find direction to target

#

go

ashen yoke
#

not even necessary

#

you can use flow field

#

one fill of the graph per frame and all enemies know direction to player by sampling direction vector of the cell they are in

#

almost zero cost per agent

west lotus
#

Why every frame. Time slicing it based on the distance to player would be even better

ashen yoke
#

yeah you can tick it, but even every frame it would have small fraction of cost

#

compared to computing paths

rugged spear
#

There are a number of optimizations that can be done definitely, the real question is whether they need and/or are willing to implement them

dawn nebula
#

Just want to mention

#

not making Vampire Survivor game

#

just gave a sorta extreme example for the number of drops on the ground

#

something like uuuuh

#

Enter the Gungeon is probably the best comparison?

#

Bullet Hell-y

#

lots of projectiles

novel kayak
rugged spear
#

Personally I would say only optimize when needed, otherwise you're probably wasting your time on something that probably isn't even an issue to begin with

#

Most modern hardware will be able to cope just fine

#

It's definitely another story if you're specifically targeting older hardware, but you can only find out one way or another

ashen yoke
#

i agree, KISS it first

#

see if it works as is

novel kayak
#

Can someone help me with the Load Method using System.Runtime.Serialization.Formatters.Binary

I don't know how to display the items.I'm sure that the items are saved because i've looked into the binary file.

So the problem is that the RetriveItemList() is always log (Item list is empty)

(The materials are displayed correctly)

rugged spear
#

I definitely understand the natural feeling to write "the best, highly optimized"ℒ️ code that will run on a potato, but today most computers can run insanely fast and unless it becomes an issue down the road then just don't worry about it until you need to.

rugged spear
novel kayak
rugged spear
rugged spear
#

where do you populate the rewards.itemList variable

#

So where is the code that loads the itemList from the file

novel kayak
#

First image sent,is loading materials(which is working) but cant load the items correctly

rugged spear
#

I see you do rewards.materials = loadedData.materials; but you never do rewards.itemList = loadedData.itemList in the LoadData() method

#

private void RetrieveItemList(List<Item> itemList)
RetrieveItemList(loadedData.itemList)

novel kayak
#

Love you

rugged spear
#

in the RetrieveItemList method, remove the List<Item> itemList = rewards.itemList; line

rugged spear
novel kayak
#

Y

rugged spear
#

okay cool

#

I was trying to help you clean up your code but as long as it works that's great

novel kayak
#

can't wait to show chat gpt i'm superior kekwait

earnest gazelle
#

Hey, how to focus on a folder in unity editor?

 var folderObj = AssetDatabase.LoadMainAssetAtPath(Path.Combine(""));
            Selection.activeObject = folderObj;
            EditorUtility.FocusProjectWindow();

It is OK but I want to go to an empty folder in

swift falcon
rugged spear
#

IEnumerable<string> test = new List<string>();

#

I guess it's still writable

earnest gazelle
#

Hey, I want to initialize a field after creating a SO just once.
Using OnBeforeSerialize is OK but it does not work for asset duplication.
What about OnAfterDeserialize or OnEnable, Awake,

hot torrent
#

this code just crashed unity lucSit

main tree
#

Hello, how can I use SetActive in Photon, to hide a object for both players? I tried this way but it gives an error:

GameObject nesne = liste[0];
PhotonView photonView = GetComponent<PhotonView>();
photonView.RPC("gizle", RpcTarget.AllBuffered, nesne)

[PunRPC]
    void gizle(GameObject nesne)
    {
        nesne.SetActive(false);
    }```

The error:
``Exception: Write failed. Custom type not found: UnityEngine.GameObject``

I'm sure that "nesne" variable isn't null. I checked it.
hot torrent
fervent furnace
#

i(t)=i(t-1)*something
=i(0)^(t) and something<1
so i will never reach zero

main tree
hot torrent
#

No worries!

fervent furnace
#

oh i miss read, the correct formula should be:
i(iteration)=i(iteration-1)-i(iteration-1)*something
i(iteration)=i(iteration-1)*(1-something)<= this thing also < 1 and > 0
but the result is still the same, i never reach 0

hot torrent
#

I found a different solution anyways, thanks for tha explenation!

wicked kiln
#

hello guys im doing an isometric game and i wrote a code to generate tiles based on Perlin noice and i have an issue with the tiles they do not generate in a flat surface its like they have different elevation does anybody know how to fix it https://paste.ofcode.org/Gf74rYbaqSY58v55hnBuU3

rugged wedge
#

Hey, I got a bit stuck here so I figured I'll ask here and see if I could get some response.
My goal is to have the planet rotate constantly, and affect the ball so it rotates the same speed as the planet. But the catch is I don't want the ball to impact the planet's rotation when it's rolling over the surface of the planet. Any ideas?

wicked kiln
steady moat
#

Like topdown ?

wicked kiln
#

its isometric its flat but has the illusion that its not

steady moat
#

Oh, ok nvm I understand.

#

Do you use a single renderer ?

#

Because it seem to me that it render group of tiles by group of tiles

#

(That being said, you might want to find an alternative as performance will tank)

wicked kiln
#

i render them individully because its a small world right now but in the future this must change

steady moat
wicked kiln
#

yes i already use individual rendering

#

thanks for the try

steady moat
#

Alright, I do not really know how to fix the issue. However, I am pretty sure this is about rendering order. (And not height)

lofty crest
#

I don't understand what could be wrong, this is supposed to make it so if you hover over a button arrows appear around the button but it isnt working and i dont understand why

earnest gazelle
#

How can I recognize the type of specific scriptable object assets in AssetPostprocessor?
AssetDatabase.LoadAssetAtPath ?

native fable
#

HELP. What am I doing wrong? On the line AssetDatabase.AddObjectToAsset(sprite, savedTexture); error

private async void SaveTextures(List<ImagePiece> pieces, PiecesSpritesStorage piecesSpritesStorage)
{
    var tasks = new List<UniTask>();

    var nPieces = pieces.Count;

    for (int i = 0; i < nPieces; i++)
    {
        var id = piecesSpritesStorage.PiecesCount + i;
        var spriteTexture = _imagePieceToSpriteConverter.Convert(pieces[i]);
        byte[] spriteData = spriteTexture.EncodeToPNG();

        var path = _config.GetSavePieceTexturePath(id);

        var task = UniTask.RunOnThreadPool(() => File.WriteAllBytes(path, spriteData))
            .ContinueWith(() =>
            {
                AssetDatabase.Refresh();

                ReimportAsSprite(path);
                AssetDatabase.Refresh();

                Texture2D savedTexture = AssetDatabase.LoadAssetAtPath<Texture2D>(path);

                var sprite = Sprite.Create(savedTexture,
                    new Rect(0, 0, savedTexture.width, savedTexture.height),
                    Vector2.one * 0.5f, 100, 1, SpriteMeshType.FullRect, Vector4.zero,
                    generateFallbackPhysicsShape: true);

                AssetDatabase.AddObjectToAsset(sprite, savedTexture);
                AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(savedTexture));
                AssetDatabase.Refresh();

                Object.DestroyImmediate(savedTexture);
            });
        tasks.Add(task);
    }

    await UniTask.WhenAll(tasks);
}
sleek bough
#

@strong condor Don't cross-post. !collab

tawny elkBOT
wispy nacelle
#

I have a scriptable object in my project. I included it into an assetbundle and also had a reference to it in a scene, and 2 instances of it were created after the game starts

gray mural
#

I wonder if anyone knows one of these things:

  • How to prevent textInfo.lineCount from being 0 , when text is stringEmpty. So it should always be 1
  • How to get TMP_LineInfo and TMP_CharacterInfo even when textInfo.lineCount == 0
steady moat
wispy nacelle
steady moat
#

Maybe there is something else you can do ?

steady moat
#

Instead of using AssetBundle (If you dont want)

#

I mean, what is your issue.

#

I might know something

wispy nacelle
#

If I don't use Asset Bundle then it may not have been loaded when I need it

steady moat
#

Asset Bundle is the surest way to do it.

wispy nacelle
#

folder

steady moat
wispy nacelle
steady moat
#

Also, resource is not recommanded.

#

However, it can get the jobs done.

wispy nacelle
#

They are the assets that I need anytime

steady moat
#

Not an issue with Resource

#

I'm not saying that you should, I'm just presenting alternative.

#
  • Bundle your Scene
  • Remove your Reference from your Scene
  • Remove the Asset from the Bundle
  • Use Resources
wispy nacelle
#

Thanks

steady moat
#

You cannot have at the same time, a reference to a SO in the scene (Not Bundled) and a reference to the same SO in an AssetBundle without duplicate.

wispy nacelle
#

Probably I should make something that I can drag my SO in and store its name

signal spade
#

I have been working on procedurally generating a large world using Unity terrains. Most things are working successful except terrain stitching. It works for the most part, but in some cases (typically on higher heights) the terrain will not snap together and ends up folding. I am looping through heightmap values and connecting the first row of the new terrain to the last row of the top terrain and the first column of a new terrain to the last column of the left terrain. What I had found was it seems like after about 40m in height, the snapping starts. I added some controls to clamp the heights (not 100% working yet), but I can't fathom that this is the solution. There has to be terrains that have been developed before with wider height gaps. What am I missing here? Is it just not possible?

(Please ignore the ugliness as this is just solid color materials currently and no refined procedural noise)

thick stratus
#
    public void groundCheck()
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, Vector3.down, out hit, groundcheckDistance, ground))
        {
            isGrounded = true;
        }
        else
        {
            isGrounded = false;
        }
    }

For some reason this not detecting my ground layer when on the layer, if i change the distance to around 5 it detects the layer but when i jump it detects the layer for too long allowing like 10-15 jumps

wind palm
#

What is ground?

thick stratus
#

a public layermask

#

ive assigned it in the inspector the ground layer

dry bronze
#

I need some help regarding transform.LookAt.I basically have a planetary system with orbits and then the player would be in a sector in that system and the code is supposed to find where the stars / planets are in relation to the sector and display them as a sort of "physicalized skybox"
however, sometimes this fails and projects the planet and star at completely false positions

#
            {
                _planetCParents[i].transform.rotation = Quaternion.LookRotation((GlobalManager.Instance.CSSI._celestialBodies[i].transform.position - transform.position), transform.up);
                //_planetCParents[i].transform.rotation = _rotationObj.transform.rotation;
                _planetCObjs[i].transform.localPosition = new Vector3(_planetCObjs[i].transform.localPosition.x, _planetCObjs[i].transform.localPosition.y, Vector3.Magnitude(transform.position - GlobalManager.Instance.CSSI._celestialBodies[i].transform.position) * 1000 + 10000);
            }
#

this is the relevant code (ignore the second line, that's commented out cause it's a relic from an attempted fix that didn't work)

wind palm
dry bronze
#

it does work fine usually

#

but eventually it breaks for whatever reason

thick stratus
#

the script is on my player model and thats def above the terrain

#

i could try a sphere cast but every other raycast type ive tried has this issue

wind palm
brisk grove
#

hi

#

can any 1 help me

#

plz

thick stratus
wind palm
brisk grove
thick stratus
#

thanks

brisk grove
knotty sun
wind palm
brisk grove
#

a*

dry bronze
#

cause I'm more or less pulling my hair out cause I don't know what the problem is in the first place / what exactly causes the behaviour)

wind palm
#

Help

fading trail
#

how do i make shader code work in URP?

#

i put it on a material and it doesnt work at all

#

makes the material invis

latent latch
fading trail
#

oh thanks

swift falcon
#

Is there a better way of doing this? It feels pretty verbose but I can't find anything else that works in a similar way

    [System.Serializable]
    public struct Message
    {
        public float Speed;

        public float GetSpeed => Speed == 0 ? DEFAULTSPEED : Speed;
    }

    const float DEFAULT_SPEED = 0.025f;```
I want to make it so:
The struct has a default value for Speed 
If Speed is changed in the inspector then that value is used instead
#

Like each variable now uses up 3 lines for itself, the property and the const

        public float GetSpeed => Speed == 0 ? DEFAULT_SPEED : Speed;
        public float GetPuncMult => PunctuationMult == 0 ? DEFAULT_PUNC_MULT : PunctuationMult;
        public string GetAudioClip => string.IsNullOrWhiteSpace(AudioClip) ? DEFAULT_AUDIO : AudioClip;```
Getting long. Not a big deal but I'm always trying to write the best code possible
#

I get an error when I do that, one sec

#

Yeah it asks me to make a contructor, so I do that and assign values. Then I get a different error about not being allowed have instance property or field initializers in structs

somber nacelle
#

yep that's not allowed until c# 10 which unity probably won't support until sometime next year at the earliest

latent latch
#

oh yeah I was actually just reading that

swift falcon
#

Yeah alright I'll try that

gray mural
#
private readonly float _defaultSpeed = .025f;

[System.Serializable]
public struct Message
{
    public float Speed;

    public Message(float Speed = _defaultSpeed)
    {
        this.Speed = Speed;
    }

    public float GetSpeed => Speed;
}
swift falcon
#

That seems even more verbose

somber nacelle
#

public Message(float Speed = _defaultSpeed)
well that's not valid

twin hull
#

no errors πŸ€”

gray mural
somber nacelle
#

default parameters have to be compile time constants, not just readonly and/or static. sure they could make it a constant but unity isn't going to be calling the parameterized constructor for the struct so it doesn't matter anyway. and you cannot define a parameterless ctor on a struct until c# 10

somber nacelle
swift falcon
#

Mine is 3 lines per variable. Yours is also 3 lines + a constructor

#

Yeah true I guess, what's the benefits of that anyway

#

I'll only be assigning stuff in the inspector btw

twin hull
#

class just seems more appropriate for that, then

gray mural
#

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

gray mural
#

formatting

idle oxide
#

did I just mess up the cs part or something else?

gray mural
#

with cs

#

just write "cs" after 3 '

#
and it gonna make your code colorful
idle oxide
#

So I tried making movement for my player. When I move right the code does exactly what I want, the speed caps out at MaxSpeed but when I move left the players velocity doesn't stop at maxSpeed and I really can't figure out why that happens. Thanks in advance!

private void Update(){
   horizontal = Input.GetAxisRaw("Horizontal");
}``````cs
private void FixedUpdate(){
   Debug.Log(rb.velocity.x);
   if (rb.velocity.x >= maxSpeed){
       rb.AddForce(new Vector2(horizontal * speed* (-0.1f), 0f), ForceMode2D.Impulse);
   }
   else{
       rb.AddForce(new Vector2(horizontal*speed, 0f), ForceMode2D.Impulse);
   } 
}```
#

better?

gray mural
earnest gazelle
#

How can I recognize the type of specific scriptable object assets in AssetPostprocessor?
AssetDatabase.LoadAssetAtPath ?
Should I get all assets and check them?

gray mural
idle oxide
#

oh right I see the problem now!

#

Thank you

gray mural
#

Mathf.Abs returns absolute value of float

wind palm
#

If max speed is the max speed so is valid you probably can lose the =

gray mural
idle oxide
#

and I should add another if that checks if the velocity is positive or negative so it multiplies it by either -0.1 or 0.1

gray mural
gray mural
idle oxide
#

This code now works great!

private void FixedUpdate(){
    Debug.Log(rb.velocity.x);
    if (Mathf.Abs(rb.velocity.x) >= maxSpeed){
        if (rb.velocity.x > 0){
            rb.AddForce(new Vector2(horizontal * speed * (-0.1f), 0f), ForceMode2D.Impulse); 
        }
        else{
            rb.AddForce(new Vector2(horizontal * speed * 0.1f, 0f), ForceMode2D.Impulse);
        }
    }
    else{
        rb.AddForce(new Vector2(horizontal*speed, 0f), ForceMode2D.Impulse);
    }  
}```
gray mural
idle oxide
gray mural
#
private void FixedUpdate()
{
    Vector2 force = new Vector2(horizontal * speed, 0f);

    if (Mathf.Abs(rb.velocity.x) < maxSpeed)
        rb.AddForce(force, ForceMode2D.Force);

    rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed), rb.velocity.y);
}
gray mural
#

see in the example provided

#

I hope that works

gray mural
gray mural
gray mural
limpid spire
#

ahh, my bad, didnt see that

idle oxide
gray mural
idle oxide
#

Now my basic player controller is done! Now I move onto harder stuff lol

random oak
#

is it ok to have Reference type in a struct? how do I deal with storing a copy of the object

somber nacelle
#

copies of the struct will contain the same reference

random oak
#

If I make it null inside one of the struct will it affect the other structs?

somber nacelle
#

no

random oak
#

ok ty

somber nacelle
#

only copies of that instance of the struct will also contain null in the variable

random oak
#

perfect thx πŸ™

swift falcon
#

This is a bit weird but is there a way to assign a variable from another class in the inspector? Or a way to write down the variable name as a string then at runtime find that variable based on the string?

I'm working on NPC logic and I'm trying to figure out ways to avoid making a unique script every time I want an NPC with different triggers/logic
I want NPCs to be able to check say whether the player is grounded. Or how high a timer on a manager is. Or other various things like that
Is this possible?

fervent furnace
#

when you copy the struct you just copy the reference (pointer) but the memory address pointed wont be copyed

#

sounds like design problem
you want to check some "value" of some object in run time then you must reference to that object unless that "value" is reference type then you copy the reference

swift falcon
#

Ok so like if I did it the slow way then I could end up with like 50 scripts:

NPC 1:
if (Player.Grounded)
PlayDialogue("Ground")

NPC 2:
if (TimeManager.Time > 5)
PlayDialogue("Its Time")

NPC 3:
if (TimeManager.Time > 10 && Player.Health > 2)
PlayDialogue("Its Also Time")

NPC 4:
if (Player.Dead || BoxCast(...).collider != null)
PlayDialogue("Fourth")

Like for almost every NPC I make it's a new script which sure is fine but if it can be avoided I'll jump at the chance

grave raven
#

can someone help me create a game?

somber nacelle
tawny elkBOT
grave raven
#

could someone help me for free?

#

or is that not possible

heady iris
#

did you read the bot message

grave raven
#

i did

heady iris
#

you clearly did not, or you wouldn't be asking if people would work on your game for free

grave raven
#

i just dont know which one to click on/use

fervent furnace
#

i will consider having a abstract parent class and has a static references to those objects needed to be checked and some static functions for checking those objects then for the scripts of each type of enemy just pick up the functions on base class they needed
or even a global system that perform logic for each npc based on their type

somber nacelle
swift falcon
#

This is a no-go is it?

 private void OnValidate()
    {
        gameObject.layer = LayerMask.NameToLayer("Interactable");
    }```

SendMessage cannot be called during Awake, CheckConsistency, or OnValidate (Square: OnLayersChanged)```