#archived-code-general

1 messages · Page 200 of 1

steady moat
#

No, with vector

#

Raycast if you want to block sight with obstacles though

safe ore
#

Yeah I don't want the ai to see through walls

safe ore
#

so use ray casts, would that not be performace heavy as well?

steady moat
#

You would need both anyway.

#

You need to compare the angle between the transform.forward of the enemies and the vector form by the player and the enemies

#

If the angle is lower than a threshold, then it is visible.

safe ore
#

alright i get you

rain minnow
dense tusk
#

oy lads. i have an object that basically acts as a button, and i wanted to know what might be a good method to make it so the button can do multiple things, such as unlocking a specific door, spawning an item, resetting something, etc. i reckon i could do this by just duplicating the object and making several scripts for unique cases, but i don't think that's very efficient

rigid island
#
 public UnityEvent StuffToDo;
    public void ButtonPressed()
    {
        StuffToDo?.Invoke();
    }```
make a prefab out of button, you can then assign each button a different method or multiple ones in inspector for field StuffToDo.
wind bobcat
#

Can anybody think of why my playercontroller wouldn't be working when I build the game, but would be working in the editor?

heady iris
#

Do any of your inputs work?

wind bobcat
#

In the editor they do

green anvil
#

What would i need the value of

heady iris
wind bobcat
#

Nope, but I think I'm figuring it out

heady iris
#

I would use OnGUI() to display input values

wind bobcat
#

I believe it has to do with the script execution order

#

I'm getting a null reference in the built version while the editor doens't have that

heady iris
#

ah

#

try restarting your editor. that can reveal execution order problems

#

the order of objects will be different

#

I've caught a few issues after doing that

#

(loading a different scene might be enough)

wind bobcat
#

I might try that, but I think I have it fixed

heady iris
#

I was just thinking about that today, actually

#

It would be nice if you could scramble objects to try and suss out that kind of problem

wind bobcat
#

Got it working 🙂

#

thx for the help

spring creek
# green anvil What would i need the value of

I would look specifically at the innermost if statement:
if (__instance.gameObject.GetComponent<BoxCollider2D>().IsTouchingLayers(owp))

Is it returning the box collider actually? is the IsTouchingLayers call returning true? Is owp what you thought it was?

#

Is it even the gameObject you thought it was?

#

Btw, why not just do if (box.IsTouchingLayers(owp)) since you cached the box collider right before this?
I'm thinking the IsTouchingLayers call is the issue, since you DID cached the box collider and used it already without a nullrefexception

#

Also, I'm confused by this:

box.transform.position += new Vector3(0, 0.2f, 0);
//...
__instance.transform.position -= new Vector3(0, 99, 0);

Since box is the BoxCollider of __instance, you are modifying the same exact transform on both of those lines. You are telling it to go up .2, and down 99.
But if I understand you right, NEITHER of those things are happening?

#

Wait, as I look more, I keep getting confused.
You have this:

foreach (var obj in Resources.FindObjectsOfTypeAll<GameObject>())
{
    int owp = LayerMask.NameToLayer("OneWayPlatform");
    if (obj.layer == owp)
    {

where you find EVERY GameObject in the game, then set owp to OneWayPlatform over and over again for each one, then check if the gameobject is on that layer?
Why not just have a component on the platform and do FindObjectsOfType

Or better yet, have a list of the OneWayPlatforms and iterate that

Or EVEN better yet, use a raycast to just see what the player is standing on instead of iterating anything

umbral agate
#

Respected,
I want to move the gameobject forward and slightly upward too and rotate slightly in the local y-axis (with rigidbody add force)...
when user finger swipe up the screen.. please guide

low summit
#

hey yall i got a question

#

im currently working on a vr game and i want to obscure the players view when they start the level

#

the way the people before me did this is that they have a giant gameobject thats black and they change the alpha of the gameobject to make it not transparent

#

this works but there are a few things that don't get blocked out by the gameobject and im struggling to figure out why it doesn't

#

anything that emits some kind of light shines thru it

#

is there a different way I can implement this?

#

then when its transparent things start showing thru the block

#

whyyyyy

#

i turn the alpha to 0 and u can see things but theyre all blocked by the thing

#

except for that stupid ass plant over there

lean sail
low summit
#

u can see the lil green spec srry for the bad sc

lean sail
#

stuff shouldnt still show through your object if its alpha is set to the max, unless the geometry is kinda weird

low summit
#

i messed around with the way its rendered

#

setting render queue to alpha test makes it not show up

lean sail
low summit
#

pretty sure the object is on a canvas

#

the black fading block is what im talking abt btw

lean sail
#

ah when you said giant i assumed it was not on the canvas

low summit
#

is it like

#

a layering issue?

#

omgomgomg

#

i iddi

#

it

low summit
#

clutch af

lean sail
low summit
#

I forgot that it was attached to a canvas

#

the camera wasn't attached to it

#

and it was on the wrong layer

waxen burrow
#

is there a way to select serialized scripts from a wrapper class? I am making an inventory system, and currently I have a serialized class Item that has an instance decleared in a mono attached to a game object. Obviously I want to have different types of items all with different stats, animations etc... Would there be a way to choose which serialized class you want to wrap onto the G.O. (choosing between children of the item class), or would I have to make wrappers for each child?

somber nebula
#

I don't know too much about ScriptableObjects so this might be a dumb question, but I have one for "Dimensions", some are presets, but I'm planning on having procedurally generated dimensions. Would it be a bad idea to generate ScriptableObjects for each new procedural dimension, or should I stick to keeping those for presets only?

latent latch
somber nebula
#

Runtime

latent latch
#

Well, you can write to scriptable objects, but you can also just use plain c# classes in this case

obtuse flame
#

Is there a way to get the face normal of a collider? I have a position close to the collider and im using collider.ClosestPointOnBounds(position) to get the closest point, but is there a way for me to also get the normal of the face where this point is?

lean sail
obtuse flame
swift falcon
#

Hey I wrote
"public List<List<Job>> data;"
to contain jobs for a 2d grid and to itterate through it, I was told I can simplify it using
"foreach (Job job in data.SelectMany(jobList => jobList))"

I don't understand the parameters of SelectMany... I don't understand why I write "jobList" twice

#

Can someone maybe help me understand it? It seems a bit weird to just write it twice, especially when I don't appear to use that variable anywhere else

mellow sigil
#

It's a lambda expression that just tells SelectMany to use the list as is without modifications

swift falcon
#

I think I kinda get it? Thanks

lean sail
void stratus
#

how can i repeat an action X amount of times every X seconds

#

like if i want it to be repeated 3 times with a 2 seconds break between each time

west lotus
void stratus
#

ty

pure mortar
#

i need a little help

#

in some scripts

pure mortar
#

hm is this a serious site ?

#

i can ask here or ?

thin aurora
# pure mortar i can ask here or ?

The point is that you just specify the actual question, providing reasonable context to allow us to help you. You don't ask for the actual help, because people are not going to answer that.

golden siren
#

can someone tell me why my tilemap is messed up, i cant figure out.

thin aurora
dusky pelican
#

Hello, when i try to create an array its just creates random count for array

knotty sun
thin aurora
dusky pelican
dusky pelican
thin aurora
#

Idk

#

I have never seen it being random

dusky pelican
thin aurora
#

🤷‍♂️ Just change it

knotty sun
#

normally when you declare an array or list without creating it the inspector will chose a length it has formerly used

thin aurora
#

Unless you have an attribute above it I could not think of a reason

dusky pelican
#

Okay thank you so much guys. If it wont be a problem for me in future i will make it

bleak abyss
#

I'm trying to control a ball using torque
but the ball is going in random directions

leaden ice
#

Basically you're passing in random nonsense

cursive moth
#

Hi, I have this struct:

[Serializable]
public struct PlaceableItem
{
    public ItemSO ItemSO;
    public int ItemCount;
    public Action<int> OnCountChanged;
    public int MaxItems;
    [Tooltip("Amount the item should move for when switching planets")]
    public float HideOffset;
    public NashSet<GameObject> PlacedItems = new NashSet<GameObject>();
}

It works good but the new NashSet<GameObject>(); is giving me an error because you can't initialise things that way when using a struct.
I need it to exist because I need to access it's count and other properties and having to do an if check and assign a new value to it every time I wanna access the property is painful.
Is there anything I can do about this?

thick terrace
#

not really, this is just how structs work! you'd need to make it a class if you want to do anything other than zero initialization

cursive moth
thick terrace
#

classes and structs are pretty interchangeable in unity's serialization system, minus a few caveats, what problems were you having?

cursive moth
#

let me re-check that

thick terrace
#

you get that if you make a class that extends ScriptableObject, but a plain C# class with [Serializable] works mostly the same as a struct

cursive moth
thick terrace
#

yup!

leaden ice
#

"HashSet" is a thing though

frail meteor
#

Is it possbile to crate a SpeedTest method to check user speed from Unity?
I've done this simple script:

{
    private string url = "https://link.testfile.org/15MB";

    void Start()
    {
        StartCoroutine(DownloadAndMeasureSpeed(url));
    }

    IEnumerator DownloadAndMeasureSpeed(string url)
    {
        Debug.LogWarning("SpeedTest STARTED");

        UnityWebRequest request = UnityWebRequest.Get(url);

        float startTime = Time.time;
        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.Success)
        {
            float downloadTime = Time.time - startTime;
            float fileSizeInBytes = request.downloadedBytes;
            float fileSizeInMB = fileSizeInBytes / (1024 * 1024);
            float downloadSpeedMBs = fileSizeInMB / downloadTime;
            float downloadSpeedMbs = downloadSpeedMBs * 8; // Convert from MB/s to Mb/s


            Debug.LogWarning("File size: " + fileSizeInMB + " MB");
            Debug.LogWarning("Download speed: " + downloadSpeedMBs + " MB/s");
            Debug.LogWarning("Download speed: " + downloadSpeedMbs + " Mb/s");
        }
        else
        {
            Debug.LogError("Error downloading file: " + request.error);
        }
    }
}```
the problem is that there is a significant discrepacy between this output on editor (15Mb/s), build (0.5Mb/s) and a google speedtest (50Mb/s). Does exists some better ways to do it? and could it be reliable in the first place?
cursive moth
primal wind
#

Then make sure it's accessible (no errors, correct namespace if you have one)

slate pulsar
#

Hey, I am trying to make a procedural terrain generator, everything is fine other than the textures seem very blocky and low quality despite that the alphamap resolution is 4096 and the textures are 1024x1024.

Here is my code to generate textures:

private float[,,] GenerateTextures(int index, TerrainData data)
{
    Debug.LogFormat("Generating textures for island: {0}", index);

    var textures = TerrainSettings.TextureSettings.Textures;

    List<TerrainLayer> layers = new List<TerrainLayer>();
    for (int i = 0; i < textures.Count; i++)
    {
        layers.Add(new TerrainLayer()
        {
            name = textures[i].Texture,
            diffuseTexture = AssetManager.instance.FindTexture(textures[i].Texture),
            normalMapTexture = AssetManager.instance.FindTexture(textures[i].NormalTexture)
        });
    }
    data.terrainLayers = layers.ToArray();

    float[,,] map = new float[TerrainSettings.HeightMapResolution, TerrainSettings.HeightMapResolution, textures.Count];

    for (int x = 0; x < TerrainSettings.HeightMapResolution; x++)
    {
        for (int y = 0; y < TerrainSettings.HeightMapResolution; y++)
        {
            for (int z = 0; z < textures.Count; z++)
            {
                var texture = textures[z];
                var height = NoiseMap[index][x,y] * 100;

                bool valid = (height > texture.MinHeight && height < texture.MaxHeight) && (texture.BiomesToSpawnIn.Contains(BiomeMap[index]));
                map[x, y, z] = valid ? 1 : 0f;
            }
        }
    }

    data.SetAlphamaps(0, 0, map);
    return map;
}
heady iris
#

well, how big is the terrain?

#

Is the terrain is 1km x 1km, and your splatmap texture is 1024x1024, you get around 1 pixel per meter

#

If you want to have, say, ten pixels of blending between the grass and the sand over the span of one meter, then your terrain should be 100m x 100m

slate pulsar
#

Ah okay. Thanks.

heady iris
#

You can also try blurring the splatmaps

#

It looks like you're setting each one to one -- and only one -- layer

#

So you're always going to have hard edges

#

I dunno if there's any built-in way to do that, but you could just do a simple box blur

#

naïvely, you'd iterate over every cell and set the value to be the average of the surrounding 9 cells

#

but you could also just do a horizontal pass and a vertical pass to make it faster

#

but at that point, I'd probably be looking at using a compute shader. You could do a nice big blur on the GPU very quickly.

delicate zinc
#

i'm having an issue where float precision is shooting me in the foot, i have two nodes which i want to test if a character controller can reach the position (for AI navigation purposes).

however, this single 0.01 difference which i have no idea where its comming from is causing my comparasion to return false, which in result causes a link between the two positions to not be built

#

how can i fix this... presicion issue?

#

since its such a tiny value i was thinking about somehow removing such small presicion. but i dont know how i would do that

#

its quite annoying since it sees to be a specific issue with the mesh collider these tiles are using

delicate zinc
#

because well, just using a regular box collider doesnt have the impresicion issue

delicate zinc
#
 _mover.DestinationPosition = nodeBPosition;

                Physics.SyncTransforms();
                for (int j = 0; j < 5; j++)
                {
                    _mover.Move();
                }
                
                if (_mover.MoverFeetPosition != _mover.DestinationPosition)
                {
                    continue;
                }```
rigid island
#

are those vector3s

delicate zinc
#

yes

#

DestinationPosition and FeetPosition are vector3s

rigid island
#

hmm they use approximity behind the scenes so not sure it would be floating point imprecision

#

can't tell by this alone , would need to see more of the setup

delicate zinc
#

or at least thats my hunch yknow

#

either that or an issue i'm facing with the character controller itself, i did make sure to account for the skin width of it

#
public Vector3 CapsuleHalfHeight => new Vector3(0, (_moverCharacterController.height / 2) + _moverCharacterController.skinWidth, 0);
public Vector3 StartPosition { get; set; }
public Vector3 DestinationPosition { get; set; }
public Vector3 MoverPosition => _transform.position;
public void SetMoverPosition(Vector3 value, bool shiftByCapsuleHalfHeight)
{
    value += shiftByCapsuleHalfHeight ? CapsuleHalfHeight : Vector3.zero;
    _transform.position = value;

}
public Vector3 MoverFeetPosition => MoverPosition - CapsuleHalfHeight;```
spring creek
delicate zinc
#

but yeah, i know the issue itself, its not exactly a difficult fix

#

what bothers me is that this is only happening on what i assume is a mesh collider

#

because on a simpler collider, such as a box collider, this doesnt happen

#

which just confuses me

#

but yeah i'll go ahead and just compare distances

#

better than staying all day trying to fix such miniscule issue

spring creek
#

Ah, you're deriving the feetPosition from a division and subtraction, I take it back, this COULD be impricision

Yeah I'm not sure the fix though, sorry

delicate zinc
#

its ok

#

the compare distance is better than nothing, so thanks regardless

rigid island
#

yeah this is a head scratch for me this early morn xD

delicate zinc
#

i've been reading that there's a... less expensive way of calculating distance instead of Vector3.Distance?

#

i know its not a default emthod in the class so i'd like to know the formula so i can use it during the AI Job

rigid island
#

wat like regular - ?

delicate zinc
rigid island
#

(a-b).magnitude

delicate zinc
#

guh

#

hm

rigid island
#

or is it SqrMagnitude ?

#

i forget

delicate zinc
#

i'm... positive magnitude just square roots the sqr magnitude value

#

then again, i'd better just use distance and worry about optimmization later

nova leaf
#

i apply rb.AddRelativeForce (500, 0, 0, ForceMode.Impulse); to an enemy, but the strength of the add force is depending on the frame rate, but i only call it once and not in update/fixed update, how can i fix that?

spring creek
spring creek
nova leaf
#

i changed the frame rate in code and it changes how strong it is

spring creek
spring creek
nova leaf
#

i should, right?

spring creek
#

The navmesh agent will continue trying to affect position while addforce is going.

spring creek
nova leaf
spring creek
#

This is a good chart

nova leaf
spring creek
nova leaf
#

i actually thought of that but i was like "surely that's not the best/most professional way to do this" xD

floral coral
#

is a delagate like a void* but for multiple functions?

lean sail
hollow cosmos
#

Will Camera.main always have the right camera in the context of OnMouseDown()?

heady iris
#

I wouldn't expect anything weird to happen.

somber nacelle
hollow cosmos
#

I see. Do you know of a better way to know where a given collider was clicked?

#

It feels weird that OnMouseDown() doesn't provide that information when it definitely has it

#

(unless it does and I'm missing it somehow)

somber nacelle
#

use a raycast or the event system interfaces

heady iris
#

Did you try to do a raycast with Camera.main.ScreenPointToRay and have problems?

hollow cosmos
#

that doesn't avoid the issue of using Camera.main unfortunately

hollow cosmos
#

unity knows which camera it's using and it knows where im clicking but opts not to tell me

somber nacelle
hollow cosmos
#

i dont want my code to break just because i change a tag on my camera

somber nacelle
hollow cosmos
#

thats the issue im trying to solve

hollow cosmos
somber nacelle
#

what do you mean by that?

hollow cosmos
#

if it knows something was clicked, then it must know which camera it used to know that

#

unity should be telling me which camera was used to know that something is being clicked

somber nacelle
#

OnMouseDown doesn't provide any information.

hollow cosmos
#

hence my problem lol

somber nacelle
#

use a raycast or the event system intefaces

#

then you will have the information

hollow cosmos
#

could you walk me through how you would raycast?

#

itll highlight why that approach wouldn't solve my issue

somber nacelle
#

why don't you actually describe what it is you are actually trying to accomplish instead of making me play games to get any useful info out of you? what good would it do for me to explain how to raycast if that isn't even going to be a useful solution?
https://xyproblem.info

hollow cosmos
#

this doesn't feel like a constructive conversation

#

i feel like ive been clear about the problem im trying to solve

#

problem: i want to know where the user clicked from within my OnMouseDown hook. i dont want to use Camera.main to achieve this

somber nacelle
#

and instead of using OnMouseDown you could raycast from the mouse's position to get the object it is clicking on as well as where it clicked. or you could use the event system interfaces like IPointerClickHandler or IPointerDownHandler which conveniently provide PointerEventData

#

ideally though, you would also only have one MainCamera in the scene

hollow cosmos
#

i apologize, that was the answer i was looking for and you were right that the way i was asking was stopping us from reaching that

hollow cosmos
#

using tags is flimsy

#

but the event system approach allows me to have control by only putting the raycaster on the camera i want it on

somber nacelle
#

okay, then don't use tags or Camera.main and just track what camera you are using yourself. you should still ideally only have the one main camera in use though

hollow cosmos
#

and gives me the position information

#

thanks i got something working that im happy with

#

eventData.pointerPressRaycast.worldPosition is what i was looking for

#

from within OnPointerClick

rugged finch
#

I'm firing bullets from a firepoint at the front of a barrel. No matter what i do, the bullets fly 90 degrees to the left. This is the current situation but i've tried many configurations: GameObject newBullet = Instantiate(bulletPrefab, firePoint.transform.position, firePoint.transform.rotation);
Rigidbody rb = newBullet.GetComponent<Rigidbody>();
rb.AddForce(firePoint.transform.forward * bulletForce, ForceMode.Impulse);

heady iris
#

perhaps firePoint is just wrongly oriented

rugged finch
#

I've triple, quadrouple checked if the forward directions and rotations all line up, yet they keep flying directly to the left, even hardcoding a rotation

heady iris
#

select it in the scene view and make sure you're in Pivot + Local mode

#

ensure that the blue arrow points forward

#

if you have the scene view on Global, not Local, you'll see the orientations

craggy totem
#

Hello does somebody know how to change this

#

TO This

#

Code i use ```java
Vector3 DirToTarget = Vector3.Normalize(Target.transform.position - transform.position);
float DOT_Prodct = Vector3.Dot(transform.right, DirToTarget);

i assume that i need change this line "transform.right" but don't know to what
Thx in advance
somber nacelle
#

it usually helps to explain what you are expecting to change. also see #854851968446365696 for what to include when asking for help

heady iris
#

are you trying to get a vector that points to a target?

craggy totem
heady iris
#

Yes. I don't know what you want to do.

#

I don't know what these "0.5" and "-0.5" values mean.

rugged finch
heady iris
#

You are in Global mode.

#

Toggle this to Local.

#

(The UI might look different in older editors. Hitting X should toggle it either way)

#

You will find that the blue arrow points to the left

rugged finch
#

Yeah so the blue arrow does indeed point directly at the enemies but still the bullet flies to the left

floral coral
#

I have an object whoms orbit I want to fake: I have the orbit period (in seconds), and I want to continuously (in fixed update) update and store the current position (for saves), but I don't know how to get that. My first thought was to use a timer that increments 0.02 every fixed update, but I don't know if a very large float can even be added with a very small float (the orbit period would be pretty long)
edit: Could I use a long (long int) counter that counts up every fixed update, then divide that by 50 (fixed update frequency), then do counter / orbitPeriod? Imma try it out
edit(again): it actually seems to work

heady iris
#

(maybe disable the projectile's collider)

#

this assumes that it's non-kinematic, of course. If it's kinematic with a component moving it manually, then that's another problem entirely

rugged finch
craggy totem
# heady iris Yes. I don't know what you want to do.

Ooo, at moment i am using this code

DOT_Prodct = Vector3.Dot(transform.right, DirToTarget);

in this instance (Image 1 ) DOT_Prodct's result will = about 0.1 f , it's at Left side of car.
and it is finding dot_product according transform.right.

but i need to find dot_product according not transform.right - but transform Looked at PINK object like in Image 2 so
DOT_Prodct's result should be = about - 0.2 f ,

heady iris
#

to get a vector pointing from A to B, just compute B - A

#

so, (known.transform.position - transform.position).normalized

craggy totem
#

2 minute, i'll try

craggy totem
# heady iris so, `(known.transform.position - transform.position).normalized`

like this

        private void OnCollisionEnter(Collision collision)
            {
                var emitParams = new ParticleSystem.EmitParams();

+          //   IF I USE
-               emitParams.position = new Vector3(0, 0, 0);
+          //   It will emit particles at "Custom_SimSpace_Transform"it is for example at (257,533,1043)in world postition
+          //   So i made this thing bellow
               emitParams.position = Custom_SimSpace_Transform.position - collision.contacts[0].point;
+          //   But it works not right as shown in video

                emitParams.applyShapeToPosition = true;
                Emit_1_obj.Emit(emitParams, 30);
            }
heady iris
#

Correct.

#

also, if you want an angle, you can use Vector3.Angle or Vector3.SignedAngle

craggy totem
#

thx very much ,i'll try it in now

zinc parrot
#

Hey so say I have 6k objects
And I need to know which objects have moved/had their transforms changed
Currently what I do is I have to go through each object, check transform.HasChanged, and then do stuff based on that
is there a better/more performant way to do this kind of check?

#

because this gets pretty bad

heady iris
#

what if you stored Transform, not the Component?

zinc parrot
#

oh shit right

heady iris
#

maybe along with a Dictionary<Transform, Component>

zinc parrot
#

that has a nonzero cost

heady iris
#

It looks like about half of the time is spent in there, yeah

#

I should really benchmark that. I've tried to minimize transform accesses in the past after noticing that

zinc parrot
#

the other half is List1.GetItem

heady iris
#

that will be harder to avoid

zinc parrot
#

mhm

#

tho this is also with deep profile on

heady iris
#

Ah, I was wondering

#

That seemed weirdly slow

zinc parrot
#

yeeee

heady iris
#

Do you directly control these objects, or are they getting bumped around by physics?

zinc parrot
#

I do not directly control them

heady iris
#

gotcha

#

if you did, then it'd make sense for the object to add itself to a HashSet of changed transforms

zinc parrot
#

mhmmm

heady iris
#

It's possible that get_transform is a lot less impactful when not in deep profile

#

i.e. that it's only 10% of the runtime, not 50%

zinc parrot
#

yep that is true

#

but it stacks up

#

oh yeah that defenitely helped

#

from 13.6ms to 11.6ms

#

I wish there was a way to have them combined but not also have that worse performance so I didnt have to have mutliple lists

#

oh awit ffs I also forgot that having List.Count as a variable in a for loops definition has a cost as it calls it every iteration

#

so now its time is a mix between transform.getHasChanged and list1.GetItem

#

wait also also finally
so transforms have a haschanged
is there anything like that for lights?

#

cuz otherwise ive got this mess where I have to check and update every light

leaden ice
#

rather than iterating over all of them

zinc parrot
#

but I dont know what has moved
I aint the one moving them

leaden ice
#

who's moving them

#

how are they moving

zinc parrot
#

not up to me
making something for others to use
so its up to them how or when or why they move

#

could be physics, could be other peopls scripts, etc.

leaden ice
#

You can't reliably use Transform.hasChanged.
You don't know if a user is also trying to use that for something

#

and then you will compete with them

zinc parrot
#

heck your right...

#

I didnt thinkg about that, so what else can I do?

craggy totem
heady iris
#

The simplest way would be to rotate the vector by 90 degrees

#

Quaternion.AngleAxis(90, transform.up) * oldVector

#

assuming that transform.up points out of the screen here

#

ah, it does; I can see the gizmo cube in the top right

zinc parrot
#

how does unity handle updating light info on the GPU?

heady iris
#

what are you trying to do?

#

not "check if things have moved and update the lights"

#

explain the gameplay you are creating

zinc parrot
#

I aint creating gameplay
I am creating a renderer thingy, and for that I need to know what transforms have changed so I can update the appropriate bounding boxes on my side, and same thing for unity default lights, I need to know which ones have changed so I can update my GPU side version of those lights to the new values

hard viper
#

If I have an object with a tiled sprite renderer, and I want to scale it (like to 1:3 from 1:1), how do I make it so it doesn't render as 1 very wide object, but like the whole area is being sliced to the new area?

zinc parrot
hard viper
#

What I am getting is: if I used a sliced sprite set to 1x1, and then scale it by 3:1, it's just the same image with every pixel made 3x wider

#

If I make the sprite renderer have a width of 3, then know the whole thing is 1x9, with every pixel 3x wider

#

and if I don't use scale, then I'd need to figure out how to scale every individual component individually, and make sure nothing breaks -.-

scarlet kindle
#

Anyone know how long the delay is after SetActive(false)?

I have a script that sets a GO to inactive, then reactivates it within like 1 frame and it's not actually restarting it. As in, the Start lifecycle doesn't restart on it

#

I'm considering adding in some forced time delay with a coroutine, but i was wondering if maybe there's a better solution

leaden ice
#

SetActive is immediate

#

Start is never expected to run more than once per object, no matter how many times you activate and deactivate it

#

You should look into OnEnable which will run every time it is enabled

scarlet kindle
#

oh weird, so then I have a follow up question cuz I assumed that disabling it restarted the hook,

if a scene reloads & this GO is a Singleton instance, i am observing the Start looping again

leaden ice
lean sail
#

It is an entirely new object then

scarlet kindle
#

here's my singleton code,
you're saying that the new object gets made, and replaces the existing one?

leaden ice
#

the new object gets made

#

and destroys itself

#

and leaves the existing one alone

#

that's what line 17-21 are doing

scarlet kindle
#

oh right cuz it skips 23 if it enters that conditional

#

ok so that is what i wanted, but i'm still observing the Start of the existing one firing again... hmm

scarlet kindle
#

or something that appears that way

leaden ice
#

you can prove it with this:

Debug.Log($"Start is running on instance {GetInstanceID()}");```
#

put that inside Start

#

if you see it twice with the same number, I will believe you

scarlet kindle
#

ok i'll try it out!

#

oh you know what, idk if i actually ever tested that case! now that I think of it

#

you must be right

#

as you usually are 😛

#

i'll try the OnEnable like you mentioned instead

#

Does OnEnable qualify in the same condition as Start as well?

#

As in, could I move my Start code into OnEnable and it would cover that condition as well as the SetActive condition?

leaden ice
#

this happens:

  • when it's first created (assuming it's active from the start)
  • whenever it's enabled or the object it's attached to is activated
scarlet kindle
#

ok i think it should work for my case then i'll try it out ty 🙂

#

yep, it worked

#

thanks again!!

stark ginkgo
#

Anyone have any idea how I can add a composite outline to a set of tiles? It should look like the composite box collider, but not a collider of course, and the outline would be visible during runtime

scarlet kindle
#

I'm running into a case where it appears that a Singleton is not found on Start() for a non singleton when a new scene is loaded.

#

GameObject.Find("MainManager") is returning null

rigid island
scarlet kindle
#

no, in Start

rigid island
#

move it to Awake

scarlet kindle
#

should do Awake instead?

#

ok

#

ty!!!

rigid island
# scarlet kindle ok

btw if you have a singleton why not make it static and use that instead of GameObject.Find("MainManager")

scarlet kindle
#

true, I should be referencing the instance member of it

#

I'll fix that too, thanks

leaden ice
#

you should have an instance reference you use directly

scarlet kindle
scarlet kindle
# rigid island move it to Awake

Is using Awake also recommended for dynamically loading any Resources into a GO on it's instantiation?

I am noticing a similar type of behavior for resource loading where there appears to be a race condition. Sometimes I get a resource loaded when doing it in Start, other times I don't

rigid island
scarlet kindle
#

Yeah i've sorta made an anti-pattern in my resource loading.

I need to refactor and think of a better way. Currently I have a BattleEnemyManager that gets the groups of enemy names for a particular battle from a Singleton, it then loads a Prefab, Animator Controller, and SOs for those enemies and attaches them to an EnemyScript that uses all of them. However, because those are attached at run-time after the EnemyScript is instantiated, there are race conditions...

I'm not sure what a better approach is when you are making procedural battles?

#

I think I'm loading too many separate resources, for instance I try to load a set of actions for the enemy in Resources which is totally uncecessary. I should remove that completely, put those Actions into the SO I am loading in instead

vivid remnant
#

Does anybody have a good example of a well organized modular weapon system or know where I can find one? I'm working on a weapon system that includes both hit scan and projectile based weapons and it's working fine but there are a few things that could be better structured with regards to the weapons that fire projectiles.

rigid island
scarlet kindle
#

yep I moved them into the SO and I think it fixed that particular race condition

#

avoiding Resource loading as much as possible seems like a generally smart practice

rigid island
#

Afaik it is

stark ginkgo
#

Is there any way to reference a class with a serialize field? Not a class instance but a class itself.

#

I have a base class with a bunch of derived classes, Need to be able to pick one of these derived classes in a ScriptableObject

tawny mountain
#

Hello everyone , I have this switch statement and I'm using it for voice recognition , Does anyone have any ideas that I could make it scale better? (making it work with a larger amount of keywords/phrases I can access) Like loading text into a struck or something

switch (arg0)
        {
            case "jump":
                animator.SetTrigger(arg0);
                recordingCanvas.resultText.text = arg0;
                break;
            case "second jump":
                animator.SetTrigger(arg0);
                recordingCanvas.resultText.text = arg0;
                break;
            case "hello":
                recordingCanvas.resultText.text = arg0;
                StartCoroutine(nameof(ToggleSpeechBubble));
                virtualAnimalSpeechBubble.text = $"Well hello there";
                break;
            case "good morning":
                recordingCanvas.resultText.text = arg0;
                StartCoroutine(nameof(ToggleSpeechBubble));
                virtualAnimalSpeechBubble.text = $"Good morning to you too!";
                break;
            case "good afternoon":
                recordingCanvas.resultText.text = arg0;
                StartCoroutine(nameof(ToggleSpeechBubble));
                virtualAnimalSpeechBubble.text = $"Good afternoon";
                break;
            case "where are we":
                recordingCanvas.resultText.text = arg0;
                StartCoroutine(nameof(ToggleSpeechBubble));
                virtualAnimalSpeechBubble.text = $"Family Farm & Home!!";
                break;


            default:
                break;
        }
delicate zinc
#

i know that i can multiply a quaternion by a vector to basically "rotate" the vector, how could i do the oposite? like... idk, ""divide"" the quaternion by a vector

stark ginkgo
#

Quaternion.Inverse might apply to you

loud pagoda
#

dang it, it keeps crashing on me :<

delicate zinc
#

thanks

stark ginkgo
#

np

rigid island
tawny mountain
rigid island
tawny mountain
rigid island
stark ginkgo
stark ginkgo
rigid island
#

bcuz go big or go home 😛

stark ginkgo
#

lmfao

rigid island
#

Dict is def good enough, but yeah vector if you want to do a more complex dialogue chatbot thing

#

you can also just use other types of db that allow phrases as query , object/doc based ones

tawny mountain
proven plume
# stark ginkgo Is there any way to reference a class with a serialize field? Not a class instan...

if you want to reference the class, you'll want to reference the Type. It's not serializable by default in Unity but you could write your own serialization for it or look online for one. Storing the fully qualified name will essentially give what you need.

Alternatively, you could use MonoScript which is the type that represents a C# script file. It has a few handy helper methods, including one that will get the Type.
https://docs.unity3d.com/ScriptReference/MonoScript.html

delicate zinc
#

i'm having an issue with what i could describe as transforming points from local to world.

Down below is a picture with 4 points, enumerated from 0 to 4, these points are not Transforms, but instead local positions relative to the game object's position stored in a ScriptableObject (this later gets deserialized into structs for usage with a job)

So far i've managed to easily transform the points from local to world, since the Transform component has such capabilities (mainly Transform.TransformPoint for Local->World, and Transform.InverseTransformPoint for World->Local). so scaling the game object and moving it around the points change accordingly

#

the issue i'm having currently is when i rotate the object, by default, rotating the game object does not rotate the points accordingly, i know this is an easy fix, since i can just multiply the GameObject's rotation by the point to get the rotated point.

However, doing this is yielding me bizarre results, below is another picture of what my attempt at rotating these points yields, notice the fact that i'm rotating 45° on the Y axis, yet the resulting translation appears to be a rotation of 90°

#

Here's the code i'm using for transforming the points from world, to local, removing the calls to TransformPoint and InverseTransformPoint give me the expected rotation results, but of course, that means that the points arent properly transformed when the game object changes size or position

https://hastebin.com/share/cizayebuke.cpp

stark ginkgo
tawny mountain
#

I created the dictionary in it's own class (Image)
and use it like this in another class

if (voiceCommandDictionary.keyPhrases.TryGetValue(spkoenString, out string value))
        {
            recordingCanvas.resultText.text = spkoenString;

            StartCoroutine(nameof(ToggleSpeechBubble));

            virtualAnimalSpeechBubble.text = $"{value}";
        }
stark ginkgo
#

You can make a dictionary between the word/sentence and an all encompassing class like:
class Action
{
public bool respondsWithMessage, (if this is false, then call the callback method, if this is true just do the default response with the message variable)
public string response message,
public virtual void CallBack,
}

delicate zinc
tawny mountain
stark ginkgo
tawny mountain
#

Getting a key , method pair basically

#

Some keys will have a string value others will have a method value , or a value like animator.SetTrigger()

stark ginkgo
#

I haven't actually encountered this in c# as im more of a js person, but found something that should work:
This is a dictionary between a string, and a function that takes a string as an input and returns a bool

var dict = Dictionary<string, Func<string, bool>>

Then you can just have:

dict["hi"] = hiFunction;

where hiFunction is defined as:

bool hiFunction(string) {
  print("hello");
  return true;
}

Or you can also use an inline function, this is more popular in js:

dict["bye"] = parameter (string) => if (parameter == "string") return true;
#

They dont need to return anything or take any parameters either you can set them to void

swift falcon
#

Thinkin about how you handle params that differ...

edgy lynx
swift falcon
#

Would it be better using generics with an abstract "Command" class that it inherits from and then just have an "Execute()" function with different params? Then they can just override the one that takes the correct params?

edgy lynx
#

Because you could then have a single file/class to store all the stuff you need, and then just do a dict lookup and invoke, and you don't ever need to return anything it looks like, hence Action.

knotty kelp
#

Hello. I am trying to find a way to display gizmos in the game view for a VR game I am making. or at least a work around. I currently have exactly what I want showing at runtime in the scene view but cant see it in the game view which is what goes to my headset.

quartz folio
#

Gizmos are editor-only. If you want them to appear in a build you need to use a 3rd party package like Shapes, or draw the lines yourself

knotty kelp
#

cool I will look into shapes. Been trying to avoid drawing the lines myself as I would like them to be more like meshes

#

nvm shapes is 100$

knotty kelp
quartz folio
#

There are no options with Gizmos, no

knotty kelp
#

oh I meant with drawing the lines myself. It seems like that would only be able to produce a wire mesh.

quartz folio
#

Depending what you need, using a Line Renderer may do the job

#

but it's generally best for quite simple things

knotty kelp
#

hmm I want to render about 100 boxes according to tracking positions, visualizing the shape is very important for what I am doing as I am trying to implement basic gestures from scratch.

quartz folio
#

If they're the same size, you can model it. If they're not, you'd have to use shaders to make it resizable without deforming oddly.
If they're not scaling dynamically, line renderers may also do the job, you would have to test whether you can make an adequate box with them though

knotty kelp
#

forgive me I am not sure what you mean by "model it" the boxes would all be the same size but the size can be changed by a parameter in the editor at the moment. Could you elaborate on that?

quartz folio
#

I mean modelling it in a modelling program like blender

knotty kelp
#

what would I be modeling?

quartz folio
#

A suitable box with the wireframe thickness you want

knotty kelp
#

hmm I mean I tried using primative game object cubes but I wasnt able to instanciate them fast enough

dense tusk
# rigid island UnityEvent

i feel obligated to tell the person who taught me something i felt a wrinkle form in my brain while i did some research on that. i have been enlightened and i am now thinking in three dimensions. thanks again for the info

dense tusk
#

big facts

leaden solstice
marsh mesa
#

Is there a way to find all objects in an area without using colliders?

#

In 2D

#

I need to put them in an array

gray jolt
marsh mesa
#

I'll only have to do it once, so I think it's fine to use find..?

#

Can it work with positions tho?

hearty abyss
#

There is a better way. Track objects from the start. if it's a rectangular or a circular area - proximity check is trivial. once entered you can add them to a separate list

marsh mesa
#

Hmm

hearty abyss
#

what are you trying to do anyway

west lotus
gray jolt
marsh mesa
#

I have a rooms system in my game, and I want all the objects in a room be disabled once you leave it

#

I'm sure there could be a better way to do that, but that's the only thing I could think of

gray jolt
marsh mesa
#

Once the player is out of the room

#

The objects that are still there are disabled

west lotus
lean sail
gray jolt
fervent furnace
#

Disable parent gameobject will disable children too, unless some go are shared but in this case you cant simply use eg overlap box to do this ie your current approach

west lotus
#

Foe this case it most certainly is

marsh mesa
#

Seems so obvious now lol

#

Thanks!

gray jolt
#

do you plan to change to other rooms once player exit the room?

marsh mesa
#

I didn't really get what u mean by that

#

Like, enabling all the stuff on entering? Yeah!

#

I already have the camera system set up to work with the rooms

gray jolt
#

oh. alright. good luck with the game 🙂

marsh mesa
#

Thanks!

fervent furnace
#

=1 is assigning 1 to levelcurrent, you need ==

#

code beginner question

glacial star
#

oh ye this the wrong channel mbmb

#

ty tho

plucky aurora
#

what this name has been changed to in unity any one knows
NativeMultiHashMap

#

in burst

#

idk what was the need for change of name

versed fern
#

How do i setup a gitignore again?

#

in fork

sleek bough
#

put gitignore file in the root project directory to use it as local

#

!vc

tawny elkBOT
#
Using version control in Unity

PlasticSCM
• Git: Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory

empty wigeon
#

Hey can anyone help me with a rigidbody problem? I’m new to unity and I’m trying to make my rigidbody physics on my player work in the air so that they can maintain velocity and change the direction without accelerating. I can basically simplify the problem to this: The player is moving with a velocity with 0 drag and 0 friction, so they will just keep going if they don’t press anything. Assume the player already has velocity so they can’t speed up at all, just move around and maintain their current velocity (or stop if they wanted to). If they look in the direction of their velocity and A/D, they should turn, but maintain the same velocity. I also need to do this without manually setting the velocity, because that messes up other stuff, I just want to work with forces. The result should be that if the player is travelling forward, and presses D, they would slowly move right, making a curve until eventually they were travelling right with the same velocity as before.

tired elk
empty wigeon
#

I'm trying to work on moving in the air, but you can ignore that, just imagine that it is moving. Like an air hockey game, with 0 friction and 0 drag. @tired elk

#

Not to change orientation of character but just to be able to move around a bit

#

The problem is that for the player to move, I need to add forces, and this ends up accelerating the player to a higher velocity. But they should just maintain their velocity. I have tried for 2 days and cant find a way to balance the forces

tired elk
#

Well, if you want to move around, you'll have no choice but to alter their velocity

obtuse cape
#

For some reason, this piece of code keeps giving me an error, it is meant to move my player based on wasd, but it doesnt move at all and outputs errors.

tired elk
#

A moving object, which maintains its velocity, can't physically move around its initial trajectory

obtuse cape
#

Thats the error

tired elk
empty wigeon
#

No I'm going to change their velocity of course, but I mean I don't want to use rb.velocity =

obtuse cape
empty wigeon
#

Because that is bad practice and causes issues in everything else

obtuse cape
#

Last line

empty wigeon
#

Just to use forces

tired elk
empty wigeon
empty wigeon
knotty sun
tired elk
obtuse cape
#

But there is a rigidbody on my player

tired elk
#

That's more of a math/physic problem than a Unity issue unfortunately

empty wigeon
wicked river
#

I am trying to figure out a nice way to keep track of the amount of Nades, bullets and consumables like health the player has at any given time.
What is most common way of approaching this ?
The way I am thinking is having a Class to keep track of the amounts of item the player has. But If I think about it a little more it seems a little stupid to take that route assuming the player has 2 pistols, 3 rifles, a sniper rifle and 3 different grenades . That will then be 8 x 2 variables so 16. 2 per item. Amount held and stack limit. That is excuding the actual amount of bullets the clip can hold. Then agian I might be overthinking this. Any input would be great

tired elk
empty wigeon
empty wigeon
knotty sun
# obtuse cape

check to make sure the PlayerMovement script is not also on another object

obtuse cape
#

Nope, its only on my player

tired elk
#

How did you implement your solution ?

empty wigeon
#

should look like this

#

That's just one example scenario though. If they pressed S of course they would slow down and eventually stop

#

I've seen games have it and it seems like quite a simple setup but for some reason it is so unbelivably difficult for me. I've spent days and tried like 10 different approaches

obtuse cape
#

I have no idea what the issue is

knotty sun
tired elk
empty wigeon
obtuse cape
#

didnt output anything

#

Oh mb

#

wait

empty wigeon
obtuse cape
#

ye it still doesnt output anything in debug

knotty sun
obtuse cape
#

No they still are there

#

Just the debug message isnt showing

#

Here's the full code again

knotty sun
#

Ok, move the Debug.Log to before line 38 and try again

obtuse cape
#

Yes its

#

saying rigidbody is null

knotty sun
#

show console

obtuse cape
#

Is it because I have a camera

#

Attatched

#

Nah

#

nvm

knotty sun
#

if you double click on the message it should take you to the gameobject that generated it

obtuse cape
#

when i double click it takes me to the debu.log code

knotty sun
#

ok try this one
if (rb == null) Debug.Log($"RB is null in {gameObject.name}",gameObject);

obtuse cape
#

is any plugins causing this problem

knotty sun
#

Odd, something somewhere is Destroying your Rigidbody

obtuse cape
#

yeah

#

I have this other code

#

attatched to the camera

#

it works fine

knotty sun
#

try this.
Copy the GetComponent to above line 31

obtuse cape
#

still doesnt work

#

tried in void update too

knotty sun
#

Sorry. I'm an idiot.
your GetComponent is wrong
it sohuld be
rb = GetComponent<Rigidbody>();

obtuse cape
#

lmfao

#

Works now lol

#

Thats my fault i knew it was with the code

knotty sun
#

I'm amazed your IDE did not throw an error

obtuse cape
#

Yea exactly

#

i didnt even know you could do rb.getcomponent...

#

Thanks steve, you are a legend

knotty sun
#

of course, GetComponent can be done on any component. but doing it when that component is null and uninitialized should have thrown an error in your IDE

#

btw you would be better making rb public and filling it in the Inspector, that way you dont need the GetComponent

brazen garden
#

@obtuse cape another tip buddy is to call rb = GetComponent in start or awake, this will allow you to cache it and use it whenever rather than calling GetComponent in an update loop which can be taxing 👍

knotty sun
brazen garden
#

@knotty sun just a tip

knotty sun
brazen garden
#

That's great

#

You could of just told him to make it public to make sure it's assigned but hey hoo

knotty sun
#

I did that as well, if you could be bothered to read

sullen fern
#

I have an animation with root motion, but i want to remove the root motion and instead move the actual game object with the same distance

#

I'm currently trying to do this with a timeline by adjusting the distance traveled comparing the same animation, but one with root motion removed

#

is there a way to get the root of the moving object? the values i use to adjust this always are slightly off

shy notch
#

I have a rigidbody3d with mass 45 but after I jump it just slowly descends to the ground even though I didn't touch the gravity value, any idea what I could be doing wrong?

sullen fern
#

but collisions between objects

shy notch
#

Hmm, if I comment out my movement the jumping works as expected

my movement:
myRigidbody.AddForce(new Vector3(moveDir.x * 60f,0f,0f), ForceMode.Impulse);

my jumping:
myRigidbody.AddForce(new Vector3(0,1f,0) * 1200f, ForceMode.Impulse);

#

so I guess my movement in fixed update is interfering with it somehow?

sullen fern
#

i would assume somewhere you are directly setting the velocity

#

but if not i cant see any issue with that

shy notch
#

Do you also happen to know how I can fix my character sliding on the ground when I land and I am not setting the velocity directly?

#

Increasing the drag on the character also makes it harder for them to jump and move

#

I set the physics material of the ground with both friction values 1 and it still feels like I am on ice

steady valley
#

Hi, sorry for the ping, I had the same problem and just wanted to thank you, it solved it!! (Doing that test in both callback side, for others in the same troubles)

sullen fern
#

i think the quickest solution would be to set velocity to zero, or slow the character down when you land

sullen fern
slate pulsar
#

Hey, when I add a terrain to a gameobject like so: var terrain = island.AddComponent<UnityEngine.Terrain>(); and apply a terrain material and an alphamap, it works but the normals for the terrain layers don't show until I re-select the material in the inspector manually and I can't figure out why.

shy notch
sullen fern
#

if the answer to my question is yes, then i assume that the player doesnt lose the velocity of the x and z values when landing

#

only the y value is cancelled out

shy notch
#

Oh, I figured it out.
If you reset the rotation of the object, the physics in unity seem to get confused

#

I now froze all rotations of the character and there is no more sliding

#

Now I just need to figure out on my own how I can make my character still spin in the air

#

Can you like freeze and unfreeze specific axises in script?

sullen fern
#

like the constraints of the rigidbody?

shy notch
#

yes

sullen fern
#

yes you can

fossil dock
#

hello! I have a little issue with a script for an AR project, is there specific channel where i can get some help ?

fossil dock
#

cool thanks a lot

spring creek
#

Unless it makes more sense to ask here

#

No prob!

fossil dock
#

well its a script issue

#

so i thought it was more fitting here

spring creek
fossil dock
#

perfect thank you !

obtuse solar
#

Hi, im trying to make something that when I add a gameobject to an array in edit mode a button gets created for it ingame. is this possible? and how would i accomplish that?

hard viper
#

I do something like that frequently

#

Make a monobehaviour with a [SerializeField] private GameObject[],
and also make a prefab for the button object (so it has all the other knickknacks like the picture/text/scripts/etc

spring creek
slate pulsar
#

ok

hard viper
#

OnStart(), call a function that goes through all the gameobject array, instantiate the button prefab for it, and set the button prefab as a child of the target object on canvas where you want to house them.

#

The target object on the canvas should have a HorizontalLayoutGroup/VerticalLayoutGroup/GridLayoutGroup component to help make them not look shitty together, automatically.

#

Then, in the newly instantiated button gameobject, we need to GetComponent, to go grab either a monobehaviour component in the prefab (to help us modify the prefab easily), or just GetComponent<Button>() so we can .onClick.AddListener to tie a function to it.

obtuse solar
#

Yes it does very much! thanks :)

hard viper
#

A word of advice btw; Keep a list/dictionary/array/etc with references to all the prefab-based objects you instantiated.

#

The thing that spawned them will likely be a point of contact in case you need to get references to the button prefabs.

#

Especially if you just want to ask all the buttons to be destroyed/disabled at once

obtuse solar
#

alr thank you for the advice i will keep that in mind

proud hare
obtuse solar
#

but less complex ig

proud hare
#

i thin i know the game. like pixel isometric?

#

is a really old game, like 10 years ago now?

obtuse solar
#

yep thats the game

obtuse solar
obtuse solar
hard viper
#

do you mean you have an array of buttons that spawn gameobjects?

obtuse solar
#

no i have an array of objects

hard viper
#

that’s what I thought, so I’m confused by that comment

#

the button gets spawned

#

so clicking the button can’t spawn the button, because it’s already spawned

scarlet viper
#

Null-coalescing operators always check for reference equality and hence the discrepancy in their outcomes. For a destroyed GameObject, the reference equals null even though its actual value is not null.
so no ?? operator in unity?? 😦

rigid island
#

no

obtuse solar
#

I add my objects to an array, and when i start the game i instantiate the same number of buttons as the length of the array with my objects. when i click one of the instantiated buttons it should spawn the right object from the array

#

you get what i mean?

scarlet viper
#

sad

hard viper
#

the button spawner should be using GetComponent() on the new button’s gameobject to search for a monobehaviour that you made. This monobehaviour should have a public function so that the button-spawner can give it the information of what gameobject it is tied to

#

the button-spawner’s one responsibility is to spawn the buttons (and maybe re/despawn them). The button needs a script whose responsibility it is to do anything specific to what happens when the button is pressed.

#

Button spawner just needs to give the button handler the info of what it is tied to.

obtuse solar
#

ohhh i get it

#

thanks again

hard viper
#

sure

naive swallow
hard viper
#

My game has a lot of objects spawning/despawning/respawning. I’m thinking about changing from an object destruction strategy to object pooling method. For this, I’m contemplating making an IResettable interface so I can reset variables in components as though they are new. Is this a good idea, or is there a smarter way?

rigid island
naive swallow
#

Yeah, as long as it isn't a UnityEngine.Object

scarlet viper
rigid island
#

big sad

#

those inherit from UnityEngine.Object

scarlet viper
#

u think they will make it work in the future

somber nacelle
#

doubtful. the reason it doesn't work is because c# doesn't really have the concept of "destroyed" and unity have overloaded the == operator to check if a UnityEngine.Object has been destroyed. the null coalescing operator does not use the overloaded operators so it cannot check if the object has been destroyed

#

so using that operator with unityengine.objects can lead to MissingReferenceExceptions and other similar "your object has been destroyed but you are still trying to use it" exceptions

heady iris
#

indeed -- your GameObject variable doesn't literally become null when the game object is destroyed

#

It's just convenient to make it look like it does. "I don't even have a reference" and "I have a reference, but it's to something that was destroyed" are often handled in the same way.

meager iris
#

how can i fix my camera

#

why is it like this

sleek heath
#

not really a coding question...

rigid island
fickle lichen
#
IEnumerator JumpCooldown() // deprecated?
{
    onJumpCooldown = true;
    yield return new WaitForSeconds(.5F);
    onJumpCooldown = false;
}

async Awaitable JumpCooldown()
{
    onJumpCooldown = true;
    await Awaitable.WaitForSecondsAsync(.5F, destroyCancellationToken);
    onJumpCooldown = false;
}
```Hey I have a question about Unity 2023, are coroutines being replaced or removed and should I move on with async and await? ![pepeThink](https://cdn.discordapp.com/emojis/1096440243546230796.webp?size=128 "pepeThink") Anyone familiar? ![catStare](https://cdn.discordapp.com/emojis/1092430769508589578.webp?size=128 "catStare")
leaden ice
#

No

#

Coroutines aren't going anywhere

orchid bane
#

Will JsonUtility serialize a private field with [SerializeField] attribute?

leaden ice
#

Of course

fickle lichen
#

Huh?

leaden ice
#

It was introduced to improve unitys async/await support

fickle lichen
fickle lichen
rigid island
#

because unity doesnt cleanup async Task properly

hexed pecan
#

I see it as async/await but with coroutine functionality

#

Like waiting for the next frame etc.

leaden ice
#

Unity rarely removes things

fickle lichen
fickle lichen
heady iris
#

not really. coroutines remain extremely useful for doing work on the main thread in little increments.

leaden ice
#

Doesn't look like it supports many coroutine features

hexed pecan
rigid island
# fickle lichen Alright, but still, seems it's some replacement for coroutines

this might clear it up a bit for you
https://youtu.be/X9Dtb_4os1o

In this follow-up video, we explore the Awaitable class introduced in Unity 2023.1, which aims to improve asynchronous programming workflows.

See part 1: https://youtu.be/WY-mk-ZGAq8

Topics Covered:

  1. Learn about the new Awaitable.WaitForSecondsAsync, NextFrameAsync, EndOfFrameAsync & FixedUpdateAsync.
  2. Learn about cancellation tokens and s...
▶ Play video
fickle lichen
mental rover
rigid island
fickle lichen
fickle lichen
mental rover
#

it might take some time for the intuition to form on how async/await works, and might seem redundant for people who have already spent the time learning the intricacies of coroutines, but it's a cleaner way of doing things and much more in line with .NET standards outside of Unity (imo)

heady iris
#

I will have to break into that eventually.

hexed pecan
#

I've used async/await lately but it lacks the functionality of waiting in Unity-time instead just realtime

#

Might need to look at 2023 for awaitable then

#

Or maybe unitask?

mental rover
#

from what I can tell the 2023 awaitable implementation is effectively what UniTask has been doing for a while

fickle lichen
hexed pecan
#

Yeah they look very similiar. Might stick to 2021 for this project and try UniTask

mental rover
#

UniTask synch context is based on the unity lifecycle, it has all of the nice things like gameobject cancellation tokens on destroy, etc

hexed pecan
rigid island
fickle lichen
#

But it seems to be new in Unity

mental rover
rigid island
#

unity has async void Start for example

hard viper
#

the main thing I like about coroutines is that they are really easy to set to wait for specific parts of a frame. tied to different parts of unity’s execution order

hexed pecan
hard viper
#

given the clusterfuck of Unity’s new business model, it is a great time to learn async

hexed pecan
fickle lichen
mental rover
hexed pecan
#

Alright

silk edge
#

Hey I am trying to get some basics down for player controls. I am trying to get the player to be able to move foward and backwards, while also rotating witht he camera (in first person) also moving with the player
However I am having some trouble as the player doesnt move on inputs or rotate, and as soon as I set speed it flys off the platform

silk edge
rigid island
hard viper
#

doesn’t rotating right mean you rotate your front to up?

rigid island
#

yeah you need Vector3.up iirc

silk edge
#

I want it to turn left and right for rotate but Idk if I did that right

rigid island
silk edge
#

Oh ok thanks

kind panther
#

hi

rigid island
hard viper
#

right hand rule

#

rotation on X means X axis stays still as the yz-plane rotates around it

silk edge
#

Like as soon as I hit play the player goes flying off

rigid island
hard viper
#

horizontal input is not an input

kindred hearth
#

how do I instantiate something when a particle system gets destroyed

hard viper
#

you aren’t translating by it

silk edge
kindred hearth
#

like at each particles position

rigid island
kindred hearth
kind panther
silk edge
#

The cube on the left is the player and as soon as I hit play its like it hits something and starts tumbling off and flys away

hard viper
#

transform.Translate would need the input multiplied by vertical input or something

rigid island
# silk edge

yeah right now you're making ur object "autowalk"

hard viper
#

right now, you are programming a straight translation forever

rigid island
hard viper
#

also, you should probably lock the XY rotation of your gameobject

silk edge
#

Oh ok

kind panther
#

do u want ot move your player with input right ?

silk edge
#

Yes

hard viper
#

Translate teleports you onto the target destination

rigid island
#

and add vertical

kindred hearth
rigid island
#

h.o

hard viper
#

there is a checkbox in rigidbody (i think) for constraints, to freeze rotation. You want to block rotation on x/y

silk edge
hard viper
#

so you can only rotate along Z (which makes you turn left/right) in thr plane

hard viper
kind panther
#

yee

kind panther
#

vertical is the W/S key

silk edge
#

Ah Ok I think I am getting it then

kindred hearth
rigid island
kind panther
#

and that

kindred hearth
#

like even if the particle system hasnt ended

hard viper
rigid island
#

store their position or spawn it then when it collide

hard viper
#

this should help you understand rotation

#

rotation is done like this because it makes math with vectors immensely easier

silk edge
kindred hearth
hard viper
#

GetComponent<RigidBody>()

rigid island
hard viper
#

then take that rigidbody, and .MovePosition

hard viper
rigid island
#

it makes working from blender a pain

hard viper
#

right

rigid island
#

but w/e

hexed pecan
kind panther
silk edge
#

This is what I have updated so far

hard viper
#

anyway
Rigidbody RB = GetComponent<RigidBody>();
RB.MovePosition(vectorForNewPosition);

kindred hearth
silk edge
#

I know its probably still wrong

rigid island
# silk edge

u still need to add vertical input to translate

silk edge
#

I need to change forward don't I

rigid island
silk edge
#

Ah

hexed pecan
hard viper
#

MovePosition moves your rigidbody and checks collision as it goes from A to B

kindred hearth
hard viper
#

Translate is a straight teleport

hexed pecan
#

I dont think there is a callback for when a particle dies 🤔

hard viper
#

do you understand, mr raptor?

rigid island
#

ahh you mean individual particles

latent latch
#

This is why I write my own particle controller so I don't have to deal with unity's spiderweb API

silk edge
#

Ok so It does now take foward inputs thank you!

hexed pecan
kindred hearth
silk edge
#

Still flies away but only when I press foward lol

rigid island
#

yea

kindred hearth
#

and their positions

kindred hearth
#

is there not a single way to handle it?

rigid island
#

looking at API but not seeing individual particles

#

but has to be somewhere, I mean you can get OnCollision on each one, why not other stuff like pos/lifetime

hexed pecan
#

You can probably get all particles and check their remainingLifeTime

#

It sounds a bit hacky

kindred hearth
#

what about their pos?

hexed pecan
silk edge
#

is this correct to get the player to rotate left or right?
transform.Rotate(Vector3.up * Time.deltaTime * speed * horizontalInput);

kindred hearth
#

how would I cycle thru them

silk edge
hard viper
#

what is the matter

kindred hearth
hexed pecan
#

Maybe read the doc I linked

rigid island
# silk edge no

what is currently happening? check inspector are numbers moving ?

silk edge
#

Also It does collide with the other cubes but bounces off them and flies away

rigid island
kindred hearth
silk edge
rigid island
#

ah jeez

#

ur mixing like 3 diff things

hexed pecan
# kindred hearth oh I see it thank you :)

Again, keep in mind that this is pretty hacky because you would have to detect that the particle is about to die, while it is still alive
Just based on remainingLifeTime it will be error-prone since it might live 0 frames or it might live 2 more frames

rigid island
#

remove the rigidbody @silk edge

#

use character controller

#

switch Translate to Move

#

box collider also not needed

kindred hearth
silk edge
hard viper
#

rigidbody.MovePostion

rigid island
silk edge
#

Oh Ok

hard viper
#

character controller if you are using that

rigid island
#

public CharacterController cc

cc.Move(etc..

hexed pecan
rigid island
#

yeah but what about after

hard viper
#

don’t make these things public. just private and getcomponent

#

if your game gets big, you’ll have so many goddamn boxes to fil

rigid island
#

nah dont use get component

kindred hearth
#

what I was doing before was when an enemy was shot it spawned a bit of blood nearby

rigid island
#

you should use SerializeField

kindred hearth
#

but its better if I use particles

hexed pecan
rigid island
kindred hearth
kind panther
#

yo guys does anyone how can i make my itens stack when i pick em up to the inventory?

hard viper
silk edge
#

Is this correct?

hexed pecan
kindred hearth
rigid island
#

didnt wanna explain serializefield llol

kindred hearth
#

top down

rigid island
hard viper
#

i’m just saying don’t serialize it. you know it’s going to be there. Just GetComponent in awake

kindred hearth
#

I was maybe thinking for each particle to

#

start a coroutine

#

with the time remaining

#

and when it reachs the end

#

it spawns the blood

silk edge
#

Oh the PlayerController is not assigned

rigid island
#

the one on your player

silk edge
#

No in the script I mean

rigid island
#

or it doesn't know which one to use

hexed pecan
rigid island
hexed pecan
#

There's always VFXGraph, maybe it can support this

silk edge
#

Neveremind I see what you mean!

kindred hearth
#

I'll just do it in burst

hard viper
#

there are 2 ways to assign variables in unity. One is via C# code, where you manually tell it x = whatever. And then you have Unity Inspector, where if a field is serialized, then in the unity editor, you can drag it to a little box for the variable

hexed pecan
#

Maybe it can work if they all have the same lifetime, but idk, hacky as hell

kindred hearth
kindred hearth
#

how has no one ever think of doing something like this

#

it has to be a way

silk edge
hexed pecan
rigid island
#

Cc doesn't have rotate, you can just rotate the same way with transform @silk edge

kindred hearth
#

I'll have to look into it

latent latch
#

how much blood are you rendering

silk edge
rigid island
dusk plume
#

hi i am pretty beginner to unity and networking in general,
i use mirror and i would know how to do a variable in network that all client receive

latent latch
#

use mirror's discord

silk edge
kindred hearth
rigid island
dusk plume
rigid island
#

just like you have speed for movement

hexed pecan
dusk plume
#

i just need to learn things

latent latch
rigid island
silk edge
hexed pecan
dusk plume
rigid island
#

I coded In many languages, but mostly Hello World

rigid island
hexed pecan
dusk plume
#

you are right about networking

rigid island
#

even with programming knowledge networking is a pain

dusk plume
#

to learn basic

dusk plume
#

i am suffering

#

lol

kindred hearth
heady iris
#

networking makes everything hurt

latent latch
rigid island
#

lol

heady iris
#

including my knees

#

somehow

kindred hearth
#

but it wasnt flexible

dusk plume
kindred hearth
#

and it didnt look good

latent latch
#

make it flexiable ;)

rigid island
heady iris
#

Getting smooth movement is...hard

latent latch
#

You can always use the particle system to render locally to a GO, and handle everything else yourself

rigid island
rigid island
waxen burrow
#

hey @heady iris, Re on the [serializedRefrence] label suggestion from monday. When making serializedRefrences, should the parent class be marked that way as well, or just the childeren?
apologies for the ping

silk edge
#

Thank you again @rigid island! It rotates and moves around. Now I just need to have it push the blocks off but I think that wont need much scripting

rigid island
#

this has example code of push rigidbodies with your character controller

#

ofc you can code it yourself with some raycasts if you want to do maybe a "use" key or "push key"

heady iris
#

(you will also probably have to do add some extra attributes / derive extra interfaces, depending on the library you're using)

static bramble
#
using UnityEngine;
using System.Collections.Generic;

public class CraterCreator : MonoBehaviour
{
    public Texture2D hMap;

    public float mapScaleMultiplier;
    void Start()
    {
        GenerateTerrain();
    }

    void GenerateTerrain()
    {
        //Texture2D hMap = Resources.Load("Assets/HeightMaps/halifax.png") as Texture2D;

        List<Vector3> verts = new List<Vector3>();
        List<int> tris = new List<int>();

        int chunkSize = 250;

        for (int i = 0; i < chunkSize; i++)
        {
            for (int j = 0; j < chunkSize; j++)
            {
                verts.Add(new Vector3(i, hMap.GetPixel(i, j).grayscale * 100, j) * mapScaleMultiplier);

                if (i == 0 || j == 0) continue;

                tris.Add(chunkSize * i + j);
                tris.Add(chunkSize * i + j - 1);
                tris.Add(chunkSize * (i - 1) + j - 1);

                tris.Add(chunkSize * (i - 1) + j - 1);
                tris.Add(chunkSize * (i - 1) + j);
                tris.Add(chunkSize * i + j);
            }
        }

        Vector2[] uvs = new Vector2[verts.Count];
        for (int i = 0; i < uvs.Length; i++)
        {
            uvs[i] = new Vector2(verts[i].x, verts[i].z);
        }

        GameObject plane = new GameObject("ProcPlane");
        plane.AddComponent<MeshFilter>();
        plane.AddComponent<MeshRenderer>();

        Mesh procMesh = new Mesh();
        procMesh.vertices = verts.ToArray();
        procMesh.uv = uvs;
        procMesh.triangles = tris.ToArray();
        procMesh.RecalculateNormals();

        plane.GetComponent<MeshFilter>().mesh = procMesh;
    }
}``` so my Texture2D is my world map height map as a png. What am i doing wrong that its not letting me make the chunk size larger than 250?
silk edge
rigid island
#

you can just use transform.forward

#

transform gives you local

#

also its Z axis

silk edge
#

so Vector3.transform.forward?

rigid island
heady iris
#

transform is a variable available in every MonoBehaviour.