#archived-code-general

1 messages · Page 294 of 1

cosmic notch
#
// If the colors array is null, use the default colors from Printer_Plane
if (colors == null)
{
    colors = Printer_Plane.defaultColors;
}
    
// If the UV coordinates array is empty, select the default UV coordinates array based on the flip flag
if (uvs == null)
{
    if (!flipUv)
    {
        uvs = Printer_Plane.defaultUvs;
    }
    else
    {
        uvs = Printer_Plane.defaultUvsFlipped;
    }
}
    
// Get the SubMesh for the specified material
LayerSubMesh subMesh = layer.GetSubMesh(mat);
    
// Record the current number of vertices
int count = subMesh.verts.Count;
    
// Add the four vertices of the plane
subMesh.verts.Add(new Vector3(-0.5f * size.x, 0f, -0.5f * size.y));
subMesh.verts.Add(new Vector3(-0.5f * size.x, topVerticesAltitudeBias, 0.5f * size.y));
subMesh.verts.Add(new Vector3(0.5f * size.x, topVerticesAltitudeBias, 0.5f * size.y));
subMesh.verts.Add(new Vector3(0.5f * size.x, 0f, -0.5f * size.y));
    
// If the rotation angle is not 0, apply rotation transformation to the vertices
if (rot != 0f)
{
    float num = rot * 0.0174532924f;
    num *= -1f;
    for (int i = 0; i < 4; i++)
    {
        float x = subMesh.verts[count + i].x;
        float z = subMesh.verts[count + i].z;
        float num2 = Mathf.Cos(num);
        float num3 = Mathf.Sin(num);
        float x2 = x * num2 - z * num3;
        float z2 = x * num3 + z * num2;
        subMesh.verts[count + i] = new Vector3(x2, subMesh.verts[count + i].y, z2);
    }
}
    
// Offset the vertex coordinates by the center point, and add UV coordinates and colors
for (int j = 0; j < 4; j++)
{
    subMesh.verts[count + j] += center;
    subMesh.uvs.Add(uvs[j]);
    subMesh.colors.Add(colors[j]);
}
    
// Add triangle indices
subMesh.tris.Add(count);
subMesh.tris.Add(count + 1);
subMesh.tris.Add(count + 2);
subMesh.tris.Add(count);
subMesh.tris.Add(count + 2);
subMesh.tris.Add(count + 3);

I have this code which works on submeshes , I want o have blended edges currently they are jagged

#

These are what the edges look like now

torpid depot
#

guys ı dont know why thıs ıs lıke that happenıng

#

ı am wrıtıng random.range but always creatıng a library top there and not workıng random.range

#

this library

#

ı dont know why doıng thıs Anyone know why

cosmic rain
#

It probably resolves to System one by default.

torpid depot
#

this library lıke that

#

any library not workıng

#

what ıs the problem wıth that

#

ı dont know

dawn nebula
torpid depot
dawn nebula
#

What library?

torpid depot
#

when ı want to use random.range class ( already have ın system library) ıt add other library and not workıng

#

ı am new game devoloper and dont know how can fıx my problem

lean sail
torpid depot
dawn nebula
#

So you want to use System.Random instead of Unity's implementation?

mighty juniper
torpid depot
#

because never had a problem wıth that But now dont know what ıs dıfferent

dawn nebula
#

Ok so you want to use Unity's implementation.

torpid depot
#

ı mean they just wrıts random.range and works

torpid depot
dawn nebula
#

get rid of this line

mighty juniper
# torpid depot

Because they aren’t accessing system, you are. It doesn’t know which one to choose so it just defaults to system’s implementation

dawn nebula
#

The issue is that UnityEngine has a class called "Random" and so does System.

dawn nebula
#

So when you bring in both, and try to write Random, it has no idea which you're referring to.

torpid depot
#

ı mean thıs 2 library has random thıng

#

same tıme

dawn nebula
dawn nebula
torpid depot
#

so ı need to say ıt Whıch class ı want from

#

thıs random range

dawn nebula
#

Ok so for a bit more context here.

#

There are these things called namespaces.

#

When you write out classes you can specify which namespace they belong under.

#

Putting code within namespaces is useful because it prevents conflicts.

#

If you bring in 2 libraries that both have a class called "Event" or whatever, then there'd be a conflict.

#

Since how is the program supposed to know which Event class you're referring to?

torpid depot
#

ı undurstand what u mean

#

so can ı use thıs namespace thıng for all thıs classes?

dawn nebula
#

UnityEngine is a namespace that contains a lot of the basic Unity classes.

#

System is a namespace that contains a lot of the basic C# utilities.

#

They both have a class called Random.

torpid depot
#

can ı put unıtyengıne and system namespaces ın same namespace?

#

for fıx that error

dawn nebula
#

No namespaces are separate.

fervent furnace
#

You cant, they are not created by you

torpid depot
#

so namespaces are constant thıngs

#

cant be fıxed or change

dawn nebula
#

What you need to do is get rid of these 2 lines.

#

This'll get rid of the conflict.

#

Since it'll only bring in the Random class from UnityEngine.

fervent furnace
#

You are using the namespace, if they contains some classes that have same name, you need to specify which class to use

torpid depot
dawn nebula
#

It has code related to Unity.

torpid depot
#

when ı delete system namespace my c# cods can work?

dawn nebula
#

Ya System contains a lot of utility stuff but it isn't required for like... c# to work.

torpid depot
#

is that possiblke?

#

possible?

fervent furnace
#

Yes, by specify the class to be System.class if you didnt using their namespace

#

But you dont want that so just using System

torpid depot
dawn nebula
torpid depot
#

ty guys btw <3

#

@dawn nebula u not Lazy lıke your name btw

#

u so smart xd

#

ty

dawn nebula
#

no problem

ocean hollow
eager creek
#

Ok

old linden
#

I'm working with newtonsoft Json here. How can I return this list with the underlying values? It seems to return the data type

mighty juniper
#

Hey all, I'm trying to create my own object pooling in unity, and in order to reference different pools I have a dictionary containing the GameObject of the pool i want, and the Pool class itself. However, when trying to run my GetPooledObjects() function from an external script, passing in an instance of the same GameObject in the pool, it logs the warning. Heres the function:

    public void RePoolObject(GameObject obj)
    {
        if (!poolsDict.ContainsKey(obj))
        {
            Debug.LogWarning("Pools Dict does not contain the prafab that is being repooled");
            return;
        };

        poolsDict[obj].RePool(obj);        
    }}```

And here's where im trying to repool it (This is inside of a script of a projectile from the pool)
```cs
    private void OnTriggerExit2D(Collider2D other)
    { // Pool projectile when out of map
        if (other.gameObject.CompareTag("Boundary"))
        
            ObjectPool.instance.RePoolObject(gameObject);
        }
    }```

If anyone knows why it's failing that would be greatly appreciated
soft shard
old linden
copper grove
#

im here i need to do so that on the spawncoords if the texture is GroundTexture execute a code.How do i do so

wide dock
#

Use something else for the key

#

Or use the object pooler provided by Unity

upper pilot
#

How can I block OnMouseEnter event from firing on my 2d sprite with UI element?
Currently I can click through UI on a 2d sprite and fire OnMouseEnter event.

mighty juniper
knotty sun
wide dock
dense crow
#

wwhy instance in unity work when it's component is disabled ?

#

here it is

#

i disabled the singleton component but it still work

quartz folio
dense crow
#

oh i got it , ty so much

#

disable the object give another result . i am a little bit confused here. are disable component and object different ?

plucky inlet
#

Hey everyone, I am currently testing out the visionOS Package with the simulator. I was reading on reddit about the simulator being able to tracke the cameras position with the tracked pose driver, but unfortunately, the position does not seem to update and accessing the transform.position just returns the start position. this might be an issue with me using the play to device feature. Did anyone else test it out and was probably able to get the code part of the actual position of the tracked pose driver? Or should it just be .transform.position and using "play to device" is just not working in this case.

thick terrace
gusty aurora
#

I have a simple behaviour, when my character walks into an enemy, the enemy pushed him away. But if my character dashes into an enemy, then he kills the enemy. Would you put all that logic onto the character, or onto the enemy, or a bit on both ?

hard viper
#

a bit on both

#

depending on how unique the behaviour is determines if it should be on the player or enemy. if only 2 out of 20 enemy types behave like this, then on the enemy

#

either way, both enemy and player need a script on them that exposes player state and enemy vulnerabilities, so that your script can do the logic

mighty juniper
#

Hey all, I'm trying to access a GameObject's script, however am running into some issues.
Inside of the script i have a variable that references the script i am setting it up from. I'm trying to run the function MoveToPlanet(), which relies on that variable being set. However when trying to do so it gives me the usual Object reference not set to instance... error. Despite calling the function after setting it, does anyone know what i may be doing wrong? (The reason i cant run it on Start() is because these are pooled objects). Thanks

        Enemy enemyScript = enemy.GetComponent<Enemy>();
        enemyScript.GameController = this;
        enemyScript.MoveToPlanet();```
somber nacelle
#

what line is the null reference exception actually on? if it is the first one you've shown then enemy is null. otherwise you need to look at where the error is actually coming from

fresh cosmos
#

should i use if(myScene == new Scene()) or compare against an existing empty scene to check that a scene has nothing in it?

thin aurora
#

Instead actually check if it's empty

#

Actually, scenes are compared with a handle. Idk what that handle is though

#

Maybe an id, in which case it would also not work

fresh cosmos
#

ok, thanku. so then this should work ?

// ... 

Scene myScene = new Scene();

// ... logic to find a scene

if(myScene.rootCount == 0)
  // something

knotty sun
#

not sure why you want the new Scene() in there at all

fresh cosmos
#

it cant be null so it needs to be something. or at least thats an error im getting

knotty sun
#

it can be null

thin aurora
#

You want to check if a scene is empty, right? Why instantiate a new scene that is guaranteed to be empty?

fresh cosmos
#

Cannot convert null to 'Scene' because it is a non-nullable value type [MultiSceneTools]csharp(CS0037) is the error

thin aurora
#

Because Scene is a struct

#

What exactly is the point of this code? You're making no sense with what you're sharing

#

Why check rootCount is a Scene instance you created manually?

fresh cosmos
#

i guess i should then rethink what im doing

#

i was just trying to make a method to avoid copying the same code

thin aurora
#

Structs are value types so instead of null you'd use default, which is basically the same as what you do now

#

Structs are expected to implement a sort of comparison so you can compare against default, but again I have no idea what this handle is in the scene and I doubt it's the correct way in general

fresh cosmos
#

ah, i didnt know i could use default like that

thin aurora
#

To make it nullable, change Scene myScene = new Scene(); to Scene? myScene = null or Nullable<Scene> myScene = null

fresh cosmos
#

well since im making a method to shorten code elsewhere i wanted the method to be like bool SceneIsLoaded(string name, out Scene FoundScene) which would require me to define FoundScene

thin aurora
#

Then just return default as the out parameter and return false from the method

#

Generally the out-parameter is not expected to make sense if the method returns false

fresh cosmos
#

exactly

thin aurora
#

Also, methods like these always start with Try, to indicate it tries to do something, and will return a boolean indicating success, alongside out parameters for any additional results

fresh cosmos
velvet nest
#

Does anyone have a handy way of drawing an oblique/skewed frustum via Gizmos in unity? I've tried searching everywhere online for it but Google isn't being very helpful :/
The default Gizmos.DrawFrustum() function won't work here since it draws a regular "straight" perspective frustum, and all I've got is a projection matrix with some near/far values and a camera position/orientation. I've tried using the Gizmos.matrix to convert a regular wire cube from clip-space into world space, but with no real results (which I don't understand, as the reverse projection process ought to just be worldToCamera * projection.inverse as far as I know)

static matrix
#

any ideas on how I can get a wall-crawling enemy? like tiktiks and hollow knight
I can do inner corners fine but im not sure how to do outer corners

fathom patrol
#

Hi there! I'm in a small team of students currently developing a game that is inspired by jackbox. To allow us freedom with phone screens and input, we host a WebGL application on our server, and want to connect this to some sort of host computer via a server. Is mirror the best option here?

Both exports come from the same initial Unity file and mirror is installed. How do we bridge this connection over our server so it can be played from anywhere instead of just localhost?

For more context, we have WebGL and the standalone application working, and it can connect through localhost. The only issue is that without using localhost it does not work. The server successfully listens on 7777 (we think) but when using WebGL it should also listen for 7778 if I have to believe the documentation.

static matrix
#

this is an issue with networking
not being able to access outside of localhost is a common issue

#

you could find a tunneling service like bore

#

but i've only ever used bore for minecraft servers and never for sites

solemn raven
#

hey
is SceneManager.LoadSceneAsync(2); would also unload the current scene ? or do I need to manually unload it ?

thin aurora
crimson heron
#

I'm getting 0 returned on both AudioSource.time & AudioSource.timeSamples for any file I play. It plays fine, but the time is always 0. Is there anything I'm missing?!

leaden ice
#

Show code

crimson heron
#

Via AudioSource.PlayOneShot(AudioClip)

thin aurora
#

Share the !code of your project if you want to be helped

tawny elkBOT
mellow sigil
#

I doubt those work with PlayOneShot. You'll have to use Play instead

leaden ice
crimson heron
#

Ah, thank you. That was the gap in my knowledge.

#

Setting the clip and playing returns as expected. Appreciate it

opal ivy
#

Making an FPS game at the moment. Looking for devs who are more experienced than me to provide some input on how I should approach this system?

leaden ice
#

with an int currentBulletIndex;

opal ivy
#

Do you think having a Queue would help as well? The Queue could store the current ammo type as an int and it would go in order as the queue gets cleared?

leaden ice
#

no I don't think a queue would help

#

it would complicate things

#

A simple array is better.

opal ivy
#

Fair. But later on down the road, I want the ability for the player to be able to put whichever ammo in whichever chamber, so initially I was thinking a combination of Queue and a List/Array would be best

leaden ice
#

think:

Fire() {
  Bullet b = bullets[currentBulletIndex];
  if (b == null) {
    // CLick! Empty chamber
  }
  else {
    b.HandleFiring();
  }

  currentBulletIndex = [currentBulletIndex + 1] % ammoCapacity;
}```
leaden ice
#

that's handled by the bullet part

#

the gun just fires whatevers in it

opal ivy
#

gotcha

leaden ice
#

an Array is best suited here since you have a fixed number of chambers in the revolver

thin aurora
#

A queue would be much easier

leaden ice
#

how would a queue be easier?

#

you'd have to enqueue empties

thin aurora
#

You don't fire a different bullet out of order

leaden ice
#

how does an array make things fire out of order

#

that's what the currentBulletIndex is for

thin aurora
#

I'm saying if you keep an order like this you might aswell just use a queue

leaden ice
#

I don't see how it's simpler at all

#

explain

thin aurora
#

Shoot three bullets, enqueue three more bullets

leaden ice
#

what benefit is there

thin aurora
#

Much easier than having an array

leaden ice
#

how?

thin aurora
#

I don't understand how my example is not clear enough

leaden ice
#

the size of a queue changes

#

it doesn't fit the model at all

#

when you fire a bullet you need to enqueue an empty

thin aurora
#

Exactly

leaden ice
#

if you keep shooting without replacing, you need it to not fire anything

#

that's weird

thin aurora
#

And then the next entry is the next bullet

leaden ice
thin aurora
#

And a queue can be a static size

leaden ice
#

except reloading

leaden ice
#

it changes size every time you call Dequeue and Enqueue

#

it's just not the right model

fervent furnace
#

queue doesnt support random access

leaden ice
#

with a revolver you can put a bullet in any chamber

#

and leave any chamber empty

fervent furnace
#

=you cant insert bullet at random position

leaden ice
#

that's incredibly awkward with a Queue

thin aurora
#

You're not inserting the bullets in a random position

leaden ice
#

With the queue:

  • I fire a bullet. You say now Enqueue(null) I guess?
  • now how do I replace that null with an actual bullet? (reload)
#

i have to now dequeue the null

#

and enqueue a bullet

#

and probably rebuild the whole queue because that happens out of order

#

it's totally messed up

thin aurora
#

That's not how a queue works

#

It doesn't replace it with null

leaden ice
#

Not putting nulls in the queue would not work the way a revolver works

#

when you have an empty chamber and you pull the trigger, it does an empty click and rotates again

#

so you must put nulls in to maintain the realistic behavior of the revolver

thin aurora
#

Actually, let me correct myself. It does insert null.

#

Enqueueing a bullet will replace the first null value

leaden ice
#

how?

leaden ice
#

How would you replace a null. Queue doesn't have a "replace" function

thin aurora
#

The queue does that

leaden ice
#

it definitely does not

thin aurora
#

Check the code. A queue keeps track of the last valid item and replaces the null value by index

opal ivy
#

My initial Idea with the Queue system is that the player would be able to change which ammo would go where when they reloaded in a menu (As in a pre-made selection of ammo that could be interchanged) would be when you reload, it queues up 6 of the corresponding chambers with ammo types as integers. The integers could then be referenced to do the corresponding type of shot it would make

thin aurora
#

Either way unless this game reloads bullets in random positions it doesn't make sense to not just use a queue

#

An array also works but why write extra code when a queue does the exact thing asked

leaden ice
#

manipulating individual indices in a queue is messy

thin aurora
#

A better system might even be a stack since you probably reload the opposite way

leaden ice
#

The only thing a queue gets us here is a strong ordering of the chambers. The array gets us that too with very little fuss.

fervent furnace
#

once you need random access, the only choices left is array

#

and you implement your own stack/queue by copying the code and add the indexer....

leaden ice
#

If you have a queue with this:
[FireBullet, empty, IceBullet, empty, empty, RegularBullet]
God it will be really fucking annoying to go through this queue and replace empties

#

with an array it's really simple

#

With the queue you absolutely can't do it without dequeueing and requeieing basically everything

#

it's that simple people

#

Just think about it for a minute and you'll see an array is the simplest approach here by far.

thin aurora
#

A queue literally can't do this unless you manually insert "empty"

leaden ice
#

You HAVE TO

thin aurora
#

It's not skipping indexes

leaden ice
#

if you want revolver behavior

#

you must insert empties

#

otherwise it's not a revolver at all

thin aurora
#

Yeah if we're going to add a whole list of "what ifs" to this question then I'm sure arrays eventually are a better choice

#

But this was never asked

hexed oak
#

Is there an event I can listen for in any type of renderer that could tell me when the material has changed?

leaden ice
#

I'm don't see how it's a what-if. They specifically asked for revolver behavior

opal ivy
#

Live reaction atm:

leaden ice
#

with pictures and everything

leaden ice
thin aurora
#

Boy I wonder what feature would allow me to take the first entry of a collection and update it

leaden ice
#

it's a requirement

thin aurora
#

No, you argue because you assume this solution needs a million edge cases that might be added

leaden ice
#

wjhatever

#

go with the queue

#

it will not work

#

and they'll be back lol

#

just try it, it won't work like a revolver

opal ivy
leaden ice
#

you need an array

#

a queue will not do what you want.

#

But if you are in love with a queue feel free to try it and see that for yourself.

opal ivy
#

just making sure I have all the ground here for how it will function covered

hexed oak
#

Could a linked list work, of size magazine size (6)--a queue kind of assumes a starting point, but a revolver allows you to start from any given node

fervent furnace
#

an array for fixed-size magazine is better, then you maintain a current pointer indicate the next round, as PreatorBlue said

leaden ice
leaden ice
#

the "looping" behavior is like the least important/least difficult speedbump here

hexed oak
#

sometimes the trivial solution is the best

#

anyways, by chance is there an event I can listen for in any type of renderer that could tell me when the material has changed?

leaden ice
#

There is not

chilly surge
#

If you want to model a revolver that's fixed sized, using a fixed sized data structure seems like the straight forward logical choice if you ask me.

leaden ice
opal ivy
#

Thanks for the input though guys, I'll make a copy of the project and I'll attempt an array in one copy after a bit of research and I'll attempt a queue build in the other and see what works best

hexed oak
#

It's being changed via animation, so I'd have to keyframe it

fervent furnace
#

In computer science, a circular buffer, circular queue, cyclic buffer or ring buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end. This structure lends itself easily to buffering data streams. There were early circular buffer implementations in hardware.

hexed oak
#

dealing with adding hundreds of keyframes possibly

#

^ similar to the circularly linked list

hard viper
#

or, hear me out, an array

#

you should know exactly how many keyframes you have when you initialize

leaden ice
#

The circular buffer implementation is just an array, even in that article

#

But yeah this is a good article for @opal ivy to look at.

#

Because a revolver is a perfect example of a circular buffer

topaz hill
#

here is he code i am using its basically i have a particle that expands over time when there's a input along with it a sphere collider also expands the same way and i want to detect certain objects as the sphere grows but for some reason its not working at all

somber nacelle
#

!code

tawny elkBOT
topaz hill
#

idk how to usse it

somber nacelle
#

read the bot message on how to correctly share code

cedar jolt
#

Hey !

I am trying to make a chess game using Netcode. For the players, I currently have a gameobject that only have a camera at a certain angle. I want to rotate that object for each new player so they face each other in a 3d world. In this code, I don't see the "player.transform.Rotate(0, rotationY, 0, Space.Self);" doing anything.

foreach (ulong clientID in clientsCompleted) {
    
    GameObject player = Instantiate(playerObject, new Vector3(0,0,0), Quaternion.identity);

    player.transform.Rotate(0, rotationY, 0, Space.Self);

    player.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientID, true);

    rotationY += 180;
}
topaz hill
#

here is the code i am using its basically i have a particle that expands over time when there's a input along with it a sphere collider also expands the same way and i want to detect certain objects as the sphere grows but for some reason its not working at all

thin aurora
topaz hill
#

yes

thin aurora
#

Does it call the method at all?

somber nacelle
thin aurora
#

Try placing a debug message in it to validate

somber nacelle
#

also don't compare tags using string equality, use the CompareTag method instead

topaz hill
somber nacelle
#

have you confirmed that OnTriggerEnter is being called?

#

hint: the link i sent shows you how to ensure it is

topaz hill
somber nacelle
merry sierra
#
public void OnVertical(InputAction.CallbackContext ctx) => moveDummy = ctx.ReadValue<float>();

if(isPC)
        {
            if (!isReseting && canControl)
            {
                dynamicMoveInput = moveDummy == 0 ? 0 : Mathf.Sign(moveDummy);
                //moveInput = forwardFakeInput;
                turnInput = turnDummy == 0 ? 0 : Mathf.Sign(turnDummy);
            }
        }
        else
        {
            /*if (!isReseting && canControl)
            {
                moveInput = moveMovement.y;
                turnInput = turnMovement.x;
            }*/
        }

        moveInput = Mathf.Lerp(moveInput, dynamicMoveInput, Time.deltaTime * moveLerpSpeed);

do anyone know what is wrong with this code

thin aurora
#

Not much we can do

merry sierra
#

move input value coming as NaN

thin aurora
somber nacelle
topaz hill
somber nacelle
#

oh my god click the fucking link i sent already and go through the steps

somber nacelle
# topaz hill i did

then go through the troubleshooting steps to figure out why OnTriggerEnter is not being called. because those are the correct steps to take and if you have confirmed everything is correct according to those steps provided then it will be called

thin aurora
#

Share your !code through a paste site instead of like this please

tawny elkBOT
mighty juniper
#

Hey all, I'm working on object pooling and i was wondering one thing. I want to treat my scripts on the objects like they have just been created every time I want to grab one from the pool, how should i go about doing this?

thin aurora
somber nacelle
#

create a method on the component that your object pool will call that will do all the re-initialization

merry sierra
mighty juniper
mighty juniper
thin aurora
merry sierra
#

moveinput

thin aurora
#

But what displays it like this

merry sierra
#

lemme record a video

thin aurora
#

Thank you

merry sierra
#

it was working if i replace dynamicmoveinput to moveinput on line 96 and remove line 110

somber nacelle
#

scroll all the way up to the first error in the console, click it and see where that error is actually coming from

topaz hill
somber nacelle
#

show both objects involved in the trigger enter

ocean peak
#

hey there, i dont know if im posting in the right section but hey here we go.
I m trying to work with the ui toolkit TreeView to make a simple file explorer,
I wanted to know if and how it was possible to lazy load the tree hierarchy, by using Lazy<T> for exemple or at least dynamically load the subfolders and such
but the id system makes it kind of hard
I ve been searching but it seems like i m going in circles

topaz hill
somber nacelle
#

i mean for you to show the inspector of both objects involved in the overlap of one collider with the trigger collider that you are expecting to produce an OnTriggerEnter message

mighty juniper
# somber nacelle create a method on the component that your object pool will call that will do al...
        GameObject enemy = ObjectPool.Instance.GetPooledObject(prefab);
        Enemy enemyScript = enemy.GetComponent<Enemy>();

        enemyScript.ResetState(position ?? GetPositionOnBorder());
//Enemy class
    public void ResetState(Vector2 newPosition)
    {
        transform.position = newPosition;
        health = initialHealth;

        MoveToPlanet();
    }```

Trying to make the method like you said but the issue is for some reason im getting the usual "Object reference not set to ...." error, despite getting the component, any idea why?
somber nacelle
#

then it does not have an Enemy component

#

assuming that the error is actually coming from the line you call ResetState on

mighty juniper
#

Yeah it's coming from .ResetState() line

somber nacelle
#

that would work

topaz hill
#

1st image is the first object 2nd image the 2nd component

somber nacelle
somber nacelle
mighty juniper
#

Alright i'll do some more digging and get back to you thanks

topaz hill
somber nacelle
#

show it

topaz hill
somber nacelle
#

and what layer are both of these objects on

merry sierra
topaz hill
somber nacelle
#

and can that layer collide with itself in the layer collision matrix?

gaunt sparrow
#

is there s help channel here?

somber nacelle
tawny elkBOT
#
Where can I get help?

Take a look at #🔎┃find-a-channel

:warning: This is not a channel for official support.

Please do not ping admins, moderators, or staff with Unity issues.

topaz hill
somber nacelle
topaz hill
somber nacelle
#

ah yes, a player controller script. i am certainly familiar with your code base so i know exactly how that moves the object

#

but of course if they are part of the same object then their colliders are part of the same compound collider for the rigidbody

mighty juniper
topaz hill
somber nacelle
topaz hill
somber nacelle
#

why do you have both a rigidbody and a CharacterController on the same object?

merry sierra
#

is there a way i can make my float upto two digits

mighty juniper
# somber nacelle show the actual stack trace for your error then

Wait a minute, the error points to a different script, accessing my GameController singleton, it just conveniently happened to be on a line that made sense, i didnt read it enough. Even so though, i'm not sure why its doing that.

This is the line:

Vector2 destination = GameController.Instance.planetTransform.position;

and this is how im managing the singleton in GameController

    public static GameController Instance { get; private set; }

    private void Awake()
    {
        if(Instance == null) Instance = this;
        else
        {
            Debug.LogWarning("Duplicate GameController instances");
            Destroy(this);
        }
    }```
dim spindle
topaz hill
somber nacelle
#

yeah those two components do not mix

topaz hill
somber nacelle
#

did you though

topaz hill
#

and it works fine

topaz hill
worldly ruin
#

Hi is there a way to use Unity Collab on Unity 5.6 please? Or does anyone have any alternatives for live coding with other people? The device i want to port my game to only supports this version of the Unity Editor :/

somber nacelle
topaz hill
#

the trigger thing is still unresolved

somber nacelle
somber nacelle
#

or use a modern unity version without pirating nintendo's SDKs

worldly ruin
# lean sail Github

Github doesn't really allow live editing, if someone pushes a commit while someone is editing something then they would have to copy their progress to the new code

ocean hollow
somber nacelle
# topaz hill the trigger thing is still unresolved

yeah for a number of reasons. one being that it is a child of the collider and part of the same compound collider used by the rigidbody so why would the rigidbody think it is colliding with a different body?
second, you aren't moving the rigidbody via physics anyway so that component is pointless.
third, this should just be a physics query using an OverlapSphere rather than relying on physics messages
fourth, i already pointed out that rb and cc don't mix

merry sierra
#

not string but a variable

somber nacelle
ocean hollow
worldly ruin
topaz hill
dim spindle
somber nacelle
merry sierra
#

i need that variable i think i am getting an infinte number because there are lot of numbers after decimals

somber nacelle
#

that doesn't make any sense

worldly ruin
ocean hollow
#

A float has a specific amount of digits

lean sail
merry sierra
#

like its showing as NaN

#

moveInput *= moveInput > 0 ? fwdSpeed : revSpeed;

#

fwd speed is 50000

#

and moveinput before is 0.9999999999 something

somber nacelle
merry sierra
#

yes

worldly ruin
somber nacelle
# merry sierra yes

the only way that line could cause moveInput to be NaN was if it was already NaN or the number you multiply it by is NaN

#

in other words, your issue lies elsewhere

merry sierra
#

so i changed the fwd and rev by 1 and 1 now its giving output but if i undo it NAN

somber nacelle
#

then one or both of those values is NaN. so you need to look at where those values come from

merry sierra
#

those are value that just put in inspector and those value never change

somber nacelle
#

show the code. and the stack trace for the first error in the console

merry sierra
#

rigidbody.force assign attempt for 'Motor' is not valid. Input force is { NaN, NaN, Infinity }.
UnityEngine.Rigidbody:AddForce (UnityEngine.Vector3,UnityEngine.ForceMode)
CarMovementComponent:FixedUpdate () (at Assets/Game/Scripts/Car/CarMovementComponent.cs:166)

#

@somber nacelle see this

somber nacelle
#

okay so all of the variables involved in these calculations are public which means any other object can change them at any time so start by making sure that none of them are being modified by other objects anywhere

solemn raven
somber nacelle
#

and also print some more useful information rather than just spamming the value with no context to the console

merry sierra
#

so move input is multipling by itself with fwdspeed which is 50000 so i think its is going beyond the bounds of float (like the max float can carry)

somber nacelle
#

why are your numbers so huge anyway

ocean hollow
merry sierra
#

player is small only i think but as i put mass and stuff like to 200 it needs 50000 force power to move properly

somber nacelle
#

then don't put the mass and stuff that high

dawn nebula
#

What do you guys use when you need to execute code sequentially? Aka do X until Y, then do Z until W, then A until B. Enumerator? (Like not through Unity, just raw enumerators).

merry sierra
#

in fwd or rev speed

#

maybe issue is something else

somber nacelle
#

i mean, if you just continuously increase it forever without capping it then yeah eventually it will hit the limit that a float can store

leaden ice
dawn nebula
leaden ice
#

Kind of sounds like you are asking about a state machine

#

Coroutines and async are just lightweight state machines

brave canopy
#

What to do if I have a scene in Unity Editor opens quickly and without errors, but in the build either takes a very long time to load or does not load and gives the error Connection lost. OnStatusChanged to DisconnectByServerTimeout. Client state was: Leaving. SCS v0 UDP SocketErrorCode: 0 AppOutOfFocusRecent WinSock.I use Photon for multiplayer.The scene is loaded via Photon.Loadleve().

long hare
#

can some one help scroll up to see the issue

brave canopy
lunar python
#

idk if that applies to c#

#

but theres a hash algorithm with integer overflow

heady iris
#

that number is being multiplied by 10,000 every frame

somber nacelle
#

the issue is that they are not capping the value at all, so it reaches infinity

heady iris
#

right, but even just applying an absurd force wouldn't make a value incrase exponentially

#

you'd have to be applying an absurd force that's also proportional to the current velocity

somber nacelle
#

they are multiplying their force by like 50000 or some absurd number each frame

heady iris
#
rb.AddForce(rb.velocity);
heady iris
heady iris
dawn nebula
somber nacelle
#

dunno why they deleted the message with the link to their code, but they have this moveInput variable that they just multiply by a big ass number without ever reducing its value or clamping it 🤷‍♂️
and it all came about because they are using extreme numbers for their mass and likely drag too

heady iris
#

in fact, I've done my own coroutines at least once

#

I needed very specific control over when the enumerator had MoveNext() called on it

dawn nebula
#

So the answer is... just use an Enumerator and iterate over it?

heady iris
#

Right. That's all that Unity is doing, plus or minus the special types you can yield (e.g. WaitForSeconds)

#
myFakeCoroutines.RemoveAll(x => !x.MoveNext());
#

that's literally all I do, actually

#

ironically, I wound up using these "coroutines" to prevent two "coroutines" from running at the same time

#

...so that list is a bit pointless now

heady iris
#

this is somewhere late in LateUpdate

#

the best I could do with Unity coroutines was WaitForEndOfFrame, but that's a bit weird -- if you don't have the game view open, that never actually happens

#

it was also conceptually wrong; I wanted to do work before rendering

#

so I wrote a method that's called after all of the IK systems signal that they're done running

#

it's a late LateUpdate!

stone ginkgo
#

i'm trying to make a paper mario-style flip using thje y rotation in my game, byut when i use this code, the sprite's y rotation only changes by about 1 degrees, why is that?


        if (isFacingRight)
        {
            for (var i = 0; i < 1800; i++)
            {
                transform.Rotate(0.0f, transform.rotation.y - 0.1f, 0.0f, Space.World);
            }
        }
        else
        {
            for (var i = 0; i < 1800; i++)
            {
                transform.Rotate(0.0f, transform.rotation.y + 0.1f, 0.0f, Space.World);
            }

        }

        flipping = false;
        isFacingRight = !isFacingRight;
knotty sun
stone ginkgo
#

idk what either of those are lol, what should i do instead ?

leaden ice
heady iris
#

Quaternion.x is not an X euler angle.

knotty sun
#

well do some research. look at transform.rotation

heady iris
#

(exposing it was a mistake)

#

it's part of a vector that's used to represent the actual rotation

#

this page describes what's going on

stone ginkgo
unkempt zenith
#

I would use a tween then

#

There are many libraries for that

leaden ice
#

either way

#

you rotate 180 degrees

#

not whatever witchcraft formula you have there

stone ginkgo
leaden ice
#

just by the completely wrong amount

#

if you want to do something over time you need to use Update or a Coroutine

#

otherwise you're doing all your stuff within a single frame

#

aka instantly

#

and transform.Rotate is additive

#

if you want to rotate by 0.01, you just do Rotate(0, 0.01f, 0)

#

you wouldn't put your current rotation, in any form, as a parameter

#

but this is a bad idea

#

you don't do a hardcoded amount

#

you'd do one frame's worth

#

which will naturally depend on Time.deltaTime

unkempt zenith
#

Then again, I can only recommend a tweening library like LeanTwean to avoid hassles like these

leaden ice
#

But yeah, just use DoTween or LeanTween

rigid island
stone ginkgo
#
 {
     flipping = true;

     if (isFacingRight)
     {
         for (var i = 0; i < 1800; i++)
         {
             transform.Rotate(0.0f, 0.1f, 0.0f, Space.World);
         }
     }
     else
     {
         for (var i = 0; i < 1800; i++)
         {
             transform.Rotate(0.0f, 0.1f, 0.0f, Space.World);
         }

     }

     flipping = false;
     isFacingRight = !isFacingRight;      
 }
``` so i put this updated into a coroutine and it correctly rotates the player but not over time, it instantly changes it still
rigid island
unkempt zenith
#

Eh, is it though? All that work, figuring out the exact values, and very obscure code, and for what? When you can just do a single line like MyTweenLibrary.RotateY(obj).Time(time).Ease(ease)

Sure you can say you've done it yourself once, but is it really worth all that time and effort?

leaden ice
# stone ginkgo i'm trying to make a paper mario-style flip using thje y rotation in my game, by...
Quaternion targetRotation;

void Start() {
  targetRotation = Quaternion.identity;
}

void FlipCharacter() {
  isFacingRight = !isFacingRight;
  targetRotation = isFacingRight ? Quaternion.identity : Quaternion.Euler(0, 180, 0);
}

void Update() {
  transform.localRotation = Quaternion.RotateTowards(transform.localRotation, targetRotation, Time.deltaTime * 50);

  // demo, press F to flip
  if (Input.GetKeyDown(KeyCode.F)) FlipCharacter();
}```
Quick example
leaden ice
rigid island
#

you're not like using asset to "reinvent the wheel" you are gaining knowledge of how Quaternions / Rotation work in unity

unkempt zenith
chilly obsidian
#

Im trying to implement a pixelised effect through rendering a render texture through a raw image but I cant seem to get it to work any ideas? It outputs on the camera preview but not on the game screen

rigid island
heady iris
#

it completes instantly.

unkempt zenith
hard viper
# stone ginkgo ``` IEnumerator FlipCharacter() { flipping = true; if (isFacingRight...

the way a coroutine works is you define an IEnumerator like this;


DoX();

yield return new WaitForSeconds(4f);

DoY();

yield return null; // Wait for next frame

DoZ();

if (boolean == true) yield break; // Stop everything

yield return new WaitUntil(()=>boolean); // This waits for something else to make boolean true before we proceed

DoSomethingElse();
}```
#

understand?

stone ginkgo
#

yes that makes a lot more sense

#

im gonna install dotween like aa suiggested

unkempt zenith
#

Lol i didn't even know about wait until

#

Neat

hard viper
#

dotween is a helpful tool. coroutines are a core mechanic of unity

#

ie you don’t absolutely need dotween, but you do need coroutines

rigid island
unkempt zenith
#

It's like saying you should code a sprite animation yourself to learn about XYZ in code, instead of using the animator

#

But at least imo

unkempt zenith
hard viper
#

at any rate, he must learn the fundamentals before he takes the shortcut

unkempt zenith
#

That for sure

visual flare
#

what causes that, each time i launch the editor:

unkempt zenith
#

Sounds like a networking issue. No internet connection, proxies, that sort of thing maybe

#

But I've never done anything socket related in unity

rigid island
mighty juniper
#

Does anyone have any tutorials/documentation as to how best to implement a particle system manager? Struggling to find one

ocean hollow
mighty juniper
wraith cobalt
hard viper
#

fyi, you can’t easily refer to specific particles to turn them off

wraith cobalt
#

Yeah. Altering the particles array is an all or nothing deal.

mighty juniper
# hard viper fyi, you can’t easily refer to specific particles to turn them off

Oh right, sorry I've not really worked with them properly before, how would you do it for something like a projectile then? I initially though of just attaching a particle system to the object but the issue is when the projectile collides with something it needs to dissapear along with the particle system that was attached to it, so it wouldnt show properly. Therefore i figured the only way was to have some kind of manager where i could play specific particle effects at specific locations

ocean hollow
#

this is meant for a gun system that plays particle effects when it collides with objects, but you can modify this for your need

mighty juniper
mighty juniper
half cosmos
#

Hi, what can be used besides "GetComponent(Text).enabled = false;" in order to disable certain ui elements?

#

I'm looking to disable these elements that are a part of a canvas, using scripting

half cosmos
#

These elements would be disabled within an "Onclick" event temporarily and reactivated within another function

ocean hollow
half cosmos
#

thank you!

minor hazel
#

Hey, we have a player that can hold one item with a recipe and item scriptable object. The player currently displays the item they are holding but we want it to for example, show a lettuce and burger, we don’t know how to make it known that the player is holding a burger with lettuce or a burger without lettuce. We need it so we can make the recipe system work, but we just don’t know how to display the fact that the player is holding a burger combined with lettuce or a burger without lettuce.

ocean hollow
half cosmos
#

is there another solution?

half cosmos
#

The reason why I've made it "public Text TextBox" is because I change the dialogue within the textbox whenever necessary

lean sail
half cosmos
# ocean hollow what is your exact aim?

Basically, I'm creating an rpg and I want the dialogue and "attack" and "retreat" button to disappear in order for me to be able to present the player with a list of moves

#

Hello! is a part of the TextBox element

#

Attack and retreat, for the attack and retreat buttons

minor hazel
#

A burger is a recipe scriptsble object with a list of items that are the ingredients of it

ocean hollow
minor hazel
lean sail
#

It sounds like you just need a list of current items

minor hazel
#

we don’t know how to store what ingredients are on it

#

that’s our problem

ocean hollow
minor hazel
ocean hollow
minor hazel
#

That might work, like in the player a current item and a list of ingredients on it?

#

i don’t know why me and my friend were having such trouble thinking of that

#

brains are fried

lean sail
#

Start by just storing it anywhere

half cosmos
lean sail
ocean hollow
half cosmos
#

ok tysm lol

minor hazel
#

Like we could have a burger with lettuce and burger without at the same time

hard viper
#

is there a solid way to just block all keyboard keybinds while inputting text to an input field?

heady iris
minor hazel
#

i think we have it figured out

heady iris
#

you can define what a burger is made of with a scriptable object asset

#

If you want to allow for variations in the recipe, you could add multiple kinds of ingredients

#

mandatory vs. optional

#

you'd need a way for the recipe to describe the benefits of using an optional ingredient

minor hazel
#

i think we have an idea on how we are doing it

#

we already know how the recipe system will work, we just didn’t know how to execute it but i think we got it figured out

#

i’ll be back if we don’t

bronze fox
#

Does anyone know if the Splines package is available for 2021.3? Information about it is inconsistent accross documentation and forums, and it doesn't appear in my package manager (i.e. some forum users mention using it in that version. Documentation states 2022.1+ and 2021.3+ in different places)

heady iris
#

It looks like older versions were for 2022.1+, but later versions are supported on 2021.3+

bronze fox
#

yes I did notice that (here's the inconsistency that I mean). Any reason why I don't see it in my package manager?

lean sail
minor hazel
bronze fox
#

oh, I managed to add it using git com.unity.splines

hexed oak
#

In AudioSource there is a call that allows setting the volume scale in a PlayOneShot overload.
public void PlayOneShot(AudioClip clip, [Internal.DefaultValue("1.0F")] float volumeScale);

Is there a way I can also set the pitch of the audio source just for that one audio clip playing?

leaden ice
#

not with PlayOneShot

hexed oak
#

Right now if I change the audio source pitch it messes up subsequent audio effects

leaden ice
#

why not change it, play the clip, then change it back?

heady iris
#

i forget if that winds up changing the pitch of every one-shot that's currently playing

leaden ice
#

sounds like it might based on what they said?

heady iris
#

i know that i decided to split my UI audio source into two

#

one for most sounds and one for the varying-pitch clicks my sliders make as they're dragged around

#

i'm pretty sure i was having that exact issue

#

(then i completely replaced unity's audio system with FMOD, so it's moot now lol)

grand bobcat
#

Im really annoyed with a collider right now.

Essentialy, i have an object that has a colider, an OnMouseDown function and a script with OnTriggerEnter2D, which should only be effected, to my knowledge, by the collider on that object. But there is also a child object to that object that has a completely seperate collider, but which is also effecting the OnTriggerEnter2D and OnMouseDown, Which is weird because ive had similar systems before that havent had the same issues.

If there is anything i can do to solve this, or anything i may have messed up, please let me know

leaden ice
grand bobcat
#

is there a way i can negate it?

leaden ice
#

Any colliders that are descendants of a Rigidbody2d are part of that body

leaden ice
mighty juniper
#

Anyone know if its possible to get rid of this in VSCode?

IDE0270 Says "null check can be simplified:"

                GameObject projectile = ObjectPool.Instance.GetPooledObject(projectilePrefab);
                if (projectile == null) projectile = ObjectPool.Instance.IncreasePoolObjects(projectilePrefab, 1);```

But if i do:
```cs
 GameObject projectile = ObjectPool.Instance.GetPooledObject(projectilePrefab) ?? ObjectPool.Instance.IncreasePoolObjects(projectilePrefab, 1);```
I get "Unity objects should not use null coalescing."

So either or I get complained at
ocean hollow
mighty juniper
#

Sometimes they can be quite useful though, just not this one in particular

leaden ice
#

yes disable the specific one

mighty juniper
ocean hollow
#

GameObject projectile = ObjectPool.Instance.GetPooledObject(projectilePrefab);

#

above this line ^

mighty juniper
#

Gotcha 👍

leaden ice
#

Pretty sure you can make a .editorconfig file somewhere

ocean hollow
#

then you can restore it afterwards with #pragma warning restore IDE0270 // null check can be simplified

leaden ice
#

and disable it everywhere

mighty juniper
#

Out of curiosity, why does unity not like null coalescing?

leaden ice
#

Unity overrides the == operator

#

to check for Destroyed objects as well as null references

#

so this would actually change the behavior

mighty juniper
#

Ah right that makes sense

sterile sorrel
#

How would I find child game objects with a tag? Similar to this
' GameObject[] obstacle = GameObject.FindGameObjectsWithTag("obstacle"); '

cold parrot
leaden ice
sterile sorrel
# cold parrot https://forum.unity.com/threads/finding-all-children-of-object.453466/

you see
here
GameObject[] trainStat3EMPTY = GameObject.FindGameObjectsWithTag("trainStat3");

foreach (GameObject position in trainStat3EMPTY)
{
int randomIndex = Random.Range(0, trainStat3.Length);
GameObject randomPrefab = trainStat3[randomIndex];
Instantiate(randomPrefab, position.transform);
}

I want to find each child object with a tag and instantiate into them

vocal sorrel
#

uhhh, small question

#

i tried using the event system to have my mouse interact with the game world

#

but for some reason it only works when i click outside the game window first

#

and then click on the object that is meant to interact with the pointer

leaden ice
#

Do you have your cursor locked?

vocal sorrel
#

after that those methods stop working for some reason, unless i repeat that process

vocal sorrel
leaden ice
#

you'll have to show what you tried then

vocal sorrel
#

give a sec

chilly obsidian
#

Does anyone know of any easy ways of adding a pixelation effect to a HDRP project?

chilly obsidian
#

Thank you for the redirection

chilly obsidian
ocean hollow
vocal sorrel
#

oh

leaden ice
#

as mp4

vocal sorrel
#

yes

#

i realized haha

#

this is the clip :)

#

what should be happening is that whenever i click on one of those squares they duplicate their size

#

which happens only when i click outside the game window first

ocean hollow
#

looks like you are getting tabbed out after each click but idk what could cause that. does it also do this in a build?

solemn raven
#

hi ,
i wanna test sending a Jsong file from unity to any test server, just to test it
are there any free test servers out there I can try ?

vocal sorrel
#

i'm gonna try making a build ayways

ocean hollow
#

when you alt + tab after clicking a square, does it take you to unity (if you have more than just the editor open)?

vocal sorrel
#

haven't tried that yet

#

i am gonna try doing that after unity decides to build a single scene

#

well, making a build didn't work at all

#

it has the same problem as in the clip

ocean hollow
#

its a coding issue then

vocal sorrel
ocean hollow
#

you should review your scripts

chilly obsidian
vocal sorrel
ocean hollow
#

like i mean just look at your code

vocal sorrel
#

which confuses me, because it should work correctly

ocean hollow
#

Ig just mess around with the values in the event system 🤷‍♂️

vocal sorrel
#

could you guide me a bit on how to mess with the event system?

#

i haven't really used it before so this just becomes straight up frustating

#

unity forums don't seem to address the problem at all

sterile sorrel
graceful patio
#

whats the best apporach to
Rendering fire? on 2d

i tried using a partical system it looks mid tbh

dusk apex
graceful patio
#

perfereably a way that doesnt require too much math
but if its necesary

sterile sorrel
#

Im unsure how to make it find with a tag and instantiate on the found ones

leaden ice
dusk apex
leaden ice
sterile sorrel
#

Ok

ocean hollow
leaden ice
#

read what I wrote

ocean hollow
vocal sorrel
vocal sorrel
graceful patio
dusk apex
graceful patio
#

i think

vocal sorrel
#

i am using the new input system, that component you use is for the old input manager

vocal sorrel
ocean hollow
#

thats a bit vague

vocal sorrel
vocal sorrel
ocean hollow
#

theres no reason for that to happen, they are both independent of each other

vocal sorrel
#

do i send a screenshot?

ocean hollow
tawny elkBOT
vocal sorrel
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class GridUnit : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler
{
    [Min(1)]public int size = 5;
    public Vector2 id = Vector2.zero;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    public void OnPointerDown(PointerEventData data) 
    {
        if (data.button == 0)
        {
            transform.localScale *= 2;
        }
    }

    public void OnPointerUp(PointerEventData data)
    {
        //empty
    }

    public void OnPointerClick(PointerEventData data)
    {
        //empty
    }

    public void OnPointerEnter(PointerEventData data)
    {
        //empty
    }

    public void OnPointerExit(PointerEventData data)
    {
        //empty
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

#

like that?

#

(this is the only code using the event system in any case)

ocean hollow
heady iris
#

just to verify that you are, indeed, not receiving more than one event when you click repeatedly

vocal sorrel
#

it should run whenever i click over any of those squared

#

but it only works after "refocusing the window"

#

which is weird

#

because other than that the code actually works consistently

heady iris
#

so you added a Debug.Log statement that before the if (data.button == 0) line?

#

and it only printed once?

vocal sorrel
#

it only printed again after i did what is shown on the clip

#

the whole clicking outside the game window

heady iris
#

Do the other methods run? try adding log messages to those as well

vocal sorrel
#

those are inconsistent as well

#

they work under the same circumstances

ocean hollow
vocal sorrel
#

sorry for not answering

#

i thought i did tho

ocean hollow
# vocal sorrel default values

I've never seen something like this so I would reccomend creating a new project and replicating your setup rn to see if it still does the same thing

deep oyster
#

I've got a player character, and I've got items that might be in the world that the player might be able to pick up. How do I highlight "The closest item to the player out of the list of items that the player is in range of"

#

I guess I could just go through a list of all items every frame and check the distance of each one

#

probably not that big a deal but it feels weird

leaden ice
#

keep a list of them

#

go through that list each frame

deep oyster
#

Yeah, ok

gusty aurora
#

I would like to GetComponent<Generator<T>>() for any T that derives from a given base class.

hard viper
#

then use an interface

#

unity hates when you have generic monobehaviours anyway

#

almost every time I have a generic monobehaviour, I need to define a specific non-generic class that inherits from the generic class to make it concrete

leaden ice
gusty aurora
hard viper
#

like
FixedSpawnpointSingle : FixedSpawnpointBase<TilePlacement>

gusty aurora
#

The don't work with editor scripts, every time it's painful

hard viper
#

what

#

i’m telling you to make all your generic monobehaviours be a base class for a nongeneric one foreach specific set of generic arguments

#

wtf does this have to do with editor scripts

silver crown
#

Class Dog : Monobehaviour
Class BigDog : Dog
Class BiggerDog : BigDog

hard viper
#

class Dog<T> : MonoBehaviour
class BigDog : Dog<int>
class BlackDog : Dog<Color>

silver crown
silver crown
#

The <type> after inheritance

cosmic rain
#

That's generic types. It's what they were asking/talking about.

silver crown
hard viper
#

no. generic classes are classes with type arguments

#

like how you can have List<int>

silver crown
#

Ok, do you have an example of a use case? Or will docs have a valid demonstration?

latent latch
#

What if you want a big black dog tho

gusty aurora
#

PlanetGenerator<T> : MonoBehaviour where T : Planet

I want to do, in another script, GetComponent<xxxxx> where xxx would be anything like PlanetGenerator<Planet1>, PlanetGenerator<Planet2>, etc

#

I'm not sure if that's clearer

#

I feel like I can't use a non-generic base class here

latent latch
#

made need to type check after* component checking

leaden ice
#

GetComponent<PlanetGenerator<Planet1>>()

latent latch
#

Oh, yeah you should be. It would be concrete I'd believe

leaden ice
#

If you want ANY of the generators then you need a non generic base class or an interface

latent latch
#

you do need the constraint though, otherwise you'd type check

gusty aurora
#

so now I have PlanetGenerator<T> : PlanetGeneratorNonGeneric where T : Planet

#

but my PlanetGenerator<T> has a field public T planet

#

I can't have that field in the non-generic one

#

Generics are such a nightmare to me

latent latch
#

if you dont want to use generics, just use fields and more abstraction

gusty aurora
#

I kinda like them tbh

#

I don't like the fact you can't add them to components

#

and can't create custom editors

#

what do you call type check ?

latent latch
#

you can, but it needs to be concrete

gusty aurora
#

Run thought the list of all possible Planet1, Planet2 etc ?

latent latch
#

T: Planet isn't good enough as it could be any type which derives from Planet

latent latch
#

otherwise you're looking into serializedreferences

gusty aurora
#

So I would be replacing this

if (this.TryGetComponent<PlanetGenerator<T>>(out var planetGenerator)) { Generate(planetGenerator.planet); }

by that

if (this.TryGetComponent<PlanetGeneratorNonGeneric>(out var planetGenerator2)) { if (planetGenerator2.planet is T planet) { Generate(planet); } }

hard viper
#

Remember you can also make IGenerator

#

then GetComponent<IGenerator>

#

because it sounds like you just need to invoke a single public generator method

gusty aurora
#

I need to get the T planet in PlanetGenerator<T>

#

that's pretty much all I need

#

That's where I don't see how to use interfaces here

#

an IGenerator class couldn't have a T planet field =x

latent latch
#

if(planetGenerator2.planet is Planet planet)

#

if(planetGenerator2.planet is DerivedPlanet1 planet)
if(planetGenerator2.planet is DerivedPlanet2 planet)

heady iris
sterile sorrel
#

how would I do something like
if (transformName.transform.IsChildOf(gameObject))
but the transformName as a game object

heady iris
#

This reminds me of a problem I had. I made a class generic so that I could avoid repeating a few lines of code in each one (each class got a "Config" type with some per-class properties on it)

gusty aurora
#

Because it does

GameObject planetGO = CreateEmptyGameObject(planetName); T planet = planetGO.AddComponent<T>();

heady iris
gusty aurora
#

Also stores a reference to a T planet

heady iris
#

AddComponent has a non-generic version that takes a Type

#

The other option is to derive the generic type from a non-generic type

#

This works if the generic type is "invisible" from the outside

#

i.e. there are no public fields of type T

heady iris
gusty aurora
#

Makes sense

#

It has a public field though

[SerializeField, ReadOnly] private T _planet; public T planet { get { if (_planet == null) { _planet = GeneratePlanet(); } return _planet; } }

heady iris
#

If you must be able to get a specific type of planet out of it, then this is a non-starter -- a non-generic planet generator class wouldn't be able to actually give you a specific kind of planet

gusty aurora
#

I didn't know about passing a type to AddComponent though

heady iris
#

If you're fine with just getting a Planet out, then you can just return a Planet

still gust
#

Can anyone point me in a direction on how to start path generation. Just the steps it should take or anything else. (I'm trying to make a path on a tile based map I generated)

heady iris
#

make an abstract property on your "wrapper" PlanetGenerator class that returns a Planet, then implement it in PlanetGeneratorImplementation<T> (i don't like the name but i've had trouble coming up with a better one)

#
public abstract class PlanetGenerator {
  public abstract Planet { get; }
}

public class PlanetGeneratorImpl<T> : PlanetGenerator where T : Planet {
  protected T planet;
  public override Planet => planet;
}
gusty aurora
#

Then I would have to cast planetGenerator.Planet as T everytime I use it

#

Sounds like it could work, let me try

heady iris
gusty aurora
#

I called the first one PlanetGeneratorNonGeneric

heady iris
#

If you want to get a specific type out, you must know about the generic type.

#

But if you must know about the generic type, you're unable to reason about any kind of planet generator

#

you have to reason about a specific kind of planet generator

#

These are two incompatible ideas.

heady iris
#
if (generator.Planet is PlanetA planetA) {
  // ...
}
#

this generally suggests that you should be using polymorphism

#

Get rid of the generic type and just call virtual methods on Planet

#

I don't see how PlanetGenerator<T> makes any sense unless it's abstract

#

The generic planet generator would only be able to do things to its planet that any Planet allows

#

since all it would know is that T : Planet

gusty aurora
#

It is abstract

heady iris
#

So you have a bunch of derived classes?

#

Why do they need to be able to return a specific kind of planet instead of just giving you a Planet?

gusty aurora
#

Then I have PlanetGenerator_A : PlanetGenerator<PlanetA>

#

And for that class PlanetGenerator_A, the field public T planet from PlanetGenerator is now a public PlanetA planet

heady iris
#

actually, let me see if I can find the very long-winded discussion I had on this exact subject

gusty aurora
#

I guess they could all return a simple Planet, and then I would use is everytime I access it

heady iris
#

Why do you need to know what kind of planet the planet generator produced?

#

If you want to do something that's defined for every kind of planet, it should be a virtual method of Planet

#

if you want to do something that only works for one kind of planet, you should already know what kind of planet it is (meaning that you never have to get it from the planet generator in the first place)

gusty aurora
#

I have a bunch of other components, that add features to the newly created planet

#

if (this.TryGetComponent<PlanetGenerator<T>>(out var planetGenerator)) { AddFeature(planetGenerator.planet); }

#

In the class abstract class FeatureGenerator<T> MonoBehaviour where T : Planet

heady iris
#

oh, well, you already know T here

#

that looks fine

gusty aurora
#

As in, the planet generator is creating a barebones planet of type T, and the generators add features to it

heady iris
#

PlanetGenerator<T> is a specific type here

gusty aurora
#

The issue is that, in an derived class GravityFieldGenerator : FeatureGenerator<Planet>

#

T is planet

#

but in the associated PlanetGenerator, T could be PlanetA or PlanetB

heady iris
#

Ah, okay, this makes more sense to me

#

I was thinking you were operating without any constraints at all, and that you wanted to do something specific to each kind of planet

gusty aurora
#

Hence why I wanted to GetComponent<xxx> where xx is any class that looks like PlanetGenerator<T> where T : Planet

heady iris
gusty aurora
#

T is planet but in the associated PlanetGenerator, T could be PlanetA or PlanetB
So, when I call TryGetComponent<PlanetGenerator<T>>, I don't get any result

heady iris
heady iris
gusty aurora
#

tbf I learned about covariance a few hours ago when researching, and I realized this whole topic is way more complex than I imagined

heady iris
#

i always have to look it up to make sure i'm thinking about it the right way round

latent latch
#

if you think you need covariance you probably dont need covariance

heady iris
#

🫠

gusty aurora
#

Thanks for the help, time to ponder about what to do with all of that !

dark kindle
#
IEnumerator getSrc(string url)
{
    UnityWebRequest www = UnityWebRequest.Get(url);
    yield return www.SendWebRequest();
    if(www.result != UnityWebRequest.Result.Success)
    {
        Debug.Log(www.error);
    }
    else
    {
        if(!SaveGame.Exists("tacDate") || !SaveGame.Exists("ppDate"))
        {
            termsPopup.transform.localScale = new Vector3(1,1,1);
        }
        string txt = www.downloadHandler.text;
        string[] words = txt.Split(' ');
        foreach(string word in words)
        {
            Regex regex = new Regex(@"\d\d/\d\d/\d\d");
            Match match = regex.Match(word);

            if(match.Success && word.Contains("TAC"))
            {
                string extractedText = match.Groups[0].Value;
                _tacDate = extractedText;    
                if(SaveGame.Load<string>("tacDate") != _tacDate)
                {
                    termsPopup.transform.localScale = new Vector3(1,1,1);
                }
            }
            if(match.Success && word.Contains("PP"))
            {
                string extractedText = match.Groups[0].Value;
                _ppDate = extractedText;
                if(SaveGame.Load<string>("ppDate") != _ppDate)
                {
                    termsPopup.transform.localScale = new Vector3(1,1,1);
                }
            }
        }
    }    
}

public void onClickOk()
{
    SaveGame.Save<string>("tacDate",_tacDate);
    SaveGame.Save<string>("ppDate",_ppDate);
    termsPopup.transform.localScale = new Vector3(0,1,1);
}

I was wondering if there is way to simplify getSrc? looking for feedback

leaden ice
#
IEnumerator GetSource(string url)
{
    UnityWebRequest www = UnityWebRequest.Get(url);
    yield return www.SendWebRequest();
    if(www.result != UnityWebRequest.Result.Success)
    {
        Debug.LogError(www.error);
        yield break;
    }

    string responseData = www.downloadHandler.text;
    ProcessResponse(responseData);
}```
dark kindle
#

thank, that seem be cleaner

dark kindle
#

some time later i realize for my purpos that i didnt need (dont think i need, perhaps) for loop to all words, i parse regex in form of xx/xx/xx directly on responseData

lean sail
#

If I instantiate a scriptable object at runtime, am I supposed to destroy it myself later? Im unsure if its causing a memory leak

plucky inlet
#

What do you mean by instantiate the SO? Like create a new SO asset file or an instance at runtime?

lean sail
plucky inlet
#

Is your photon network stuff actually transferred over to the new scene or do you just replace the scene and lose all of the photon functionality?

lean sail
lean sail
#

By using the instantiate function..

plucky inlet
#

I would hook into some photon event callbacks to see, if like the match is getting destroyed or something else. Did oyu try that?

plucky inlet
lean sail
dull quarry
#
    {
        yield return new WaitForSeconds(2);
        box.enabled = false;
        yield return new WaitForSeconds(5);
        GetComponent<PhotonView>().RPC("powrot", PhotonTargets.All, ofiara , zabujca);
        GetComponent<PhotonView>().RPC("ustawienia_pocz2", ofiara);
        
    }```  ```[PunRPC]
    void ustawienia_pocz2(PhotonPlayer ofiara)
    {
        if(ofiara.isLocal)
        {
            mozesz_strzelac = false;
        }
        
    }```
plucky inlet
lean sail
#

ive read a bit of that thread, they dont seem to mention destroying it

plucky inlet
#

Even if its 2018 he posted that, it might still be the same issue. You cluttering up things while doing something SOs are not meant to be used for 😉

#

Just for testing, did you try to mimic the SOs values with an actual class/monobehaviour and use that instead of directly instantiating the SO?

lean sail
#

i dont really see how thats related, im fully aware i could just use a POCO. I just didnt want to create what is essentially a wrapper class for my SO to do that at the moment. My question at the end of the day really is just about if i am supposed to call Destroy on it. I dont really care if it affects editor performance, people arent running my game in the editor.

plucky inlet
#

Well, than I guess, I dont have the answer for you, cause I never ran into that problem. To find out, I would just try it at runtime and see if it has the same performance hit as in editor

lean sail
#

🤔 i am doing all of this at runtime

plucky inlet
#

Oh, so you profiled your runtime, sorry, wasnt clear about that

lean sail
plucky inlet
#

Well, than I think you already answered it yourself. You gotta destroy it if you wanna use SOs out of usage scope. At least if your profiling returns that outcome of free memory after doing so

knotty sun
pure onyx
#

Hello i don't know where to ask

I have a problem same like this forum https://forum.unity.com/threads/alternative-to-mobile-particles-additive-shader.1286603/
But I still haven't found the solution. Does anyone know the solution? I want to masking while using Mobile/Particles/Additive shader. Thank you

plucky inlet
lean sail
knotty sun
pure onyx
latent latch
#

you can probably just open it on the editor

pure onyx
#

oh and then add stencil properties by script ?

plucky inlet
latent latch
pure onyx
#

ok thank you

latent latch
#

there's also urp render objects that can stencil by layers, but havent really played around with it for the UI

knotty sun
knotty sun
#

@lean sail If you use Instantiate on an SO is it doing a deep or shallow copy?

latent latch
#

instantiate should work like instantiating a prefab

#

while createinstance gives you the defaults of a new instance

knotty sun
#

so shallow copy, I use my own deep copy technology for instantiating SO's

lean sail
plucky inlet
#

CreateInstance is basically what you can do with the context menu in the editor, you create a new "file"

midnight blaze
#

how can i fix my code it says theres some error at line 5,51 but i cant find the issue

latent latch
#

print to console or add breakpoints near the line of execution

midnight blaze
#

ill try

plucky inlet
midnight blaze
#

mk

#

CS1003 is the error code

knotty sun
#

what is the exact error message?

thin aurora
#

That means a character is expected where the error is

knotty sun
#

and the line of code is?

thin aurora
tawny elkBOT
quartz folio
tawny elkBOT
midnight blaze
#

Code works now

thin aurora
midnight blaze
#

mhm

#

can actually play test it now

lean sail
# knotty sun so shallow copy, I use my own deep copy technology for instantiating SO's

would this solve the issue? I have instances of a poco which all right now hold an instance of an SO. The poco itself isnt being destroyed, so im not really sure what i can do there.
These are items (poco) which hold Effects (SO). Some of these effects need to keep track of the time or some other counter, so i instantiated them or the value would be shared for every item. I can combine items, if the user picks up one they have already, it adds to a counter on item 1 and item 2 is no longer referenced.

knotty sun
#

if the POCO is not being disposed then the only way to release the SO to the GC is to null out the reference

#

you could also implement the IDisposable interface on your SO class

lean sail
#

alright thanks ill try implementing that. Worst case ill just destroy the SO in some item.Combine function but it is slightly concerning that these never got destroyed by themselves

knotty sun
#

it sounds like the problem lies with your POCO rather than with the SO

lean sail
knotty sun
onyx glade
#

Hey folks, just out of curiosity, is there a way to safely remove package data from my cache in unity? Been getting a lot of these with URP lately:

I have two different projects using URP, one of which was a copy of a project I made as a backup, which is where I think this issue is coming from. I was thinking I'd try and delete the "PackageCache/.com.unity.render-pipelines.core@14.0.10" folder and reinstall URP, but I wanted to ask some people more knowledgeable than me first before I do anything too hasty. Don't wanna mess up my whole project or make things even worse.

cold parrot
fiery sinew
#

How do survival games handle serializing and saving objects? Like when player cuts trees or builds a house.

#

there are a lot of tutorials for playerstats to json but can't find for others

onyx glade
onyx glade
#

Update: Removed & Reinstalled URP on both projects, and this seemed to have fixed it. Thanks for the help!

rocky jackal
#

How can i get the normal vector of a collider at the collision point of two objects ?

latent latch
#

doesn't collisional data give you that already

#

if you're using trigger colliders though you'd probably either raycast or compare using ClosestPoint method

rocky jackal
#

Okay, didnt know that. Thank you

latent latch
#

Probably want to iterate through them and get an average out of em

hard viper
rocky jackal
#

okay thank oyu, ill try getting the average normal vector then

hard viper
#

red shape makes contact with blue shape. You can call .GetContacts on the Collision2D, which will get you all the different contact points. And each contact point has a separate normal

#

Which gives the contacts generated at the end of the last physics sim, even if you moved shit since then

#

If you need to figure out something like, if mario is touching a goomba from the side or from above, I can recommend using Collider2D.Distance, which gives you the shortest displacement vector to bring the two things into contact

hard viper
#

if mario is touching a wall and ground at the same time, you might think the avg normal is at a 45 degree angle. But you can have multiple contacts to one face. So you might have 2 ground + 1 wall contact, 2 +2, 1+2, or 1+1. This gets very complex very fast, and none of the averages is an actual normal

latent latch
#

there's more specific averaging operations out there for this I remember coming upon

#

for those cases where you do have a lot of focused points in a specific area

hard viper
#

imo, you should only break down into contact normals when you are actually planning on reading each separately

#

like if you want mario to get contacts to check if he is touching ground and/or wall, and putting them into separate bools

#

otherwise you probably want .Distance

#

make sense?

rocky jackal
# hard viper If you need to figure out something like, if mario is touching a goomba from the...

its a bit more complicated then that, Im making a vr game with gorilla tag like movment(you can push yourself arround by hitting the ground basically) and this works by taking the difference between where the hand should be and where it actually is and it then moves the player so the two things match up and it also adds the negative player rb velocity to cancel out sliding. heres the thing i need to multiply this with a low number on steep surfaces so you can slide down them and your hands dont have much grip. But i also want you to be able to still push yourself away drom the surface your sliding on and you should be able to use 100% of your force along the direction of the normal vector so you can for example slide down a building but throw yourself in the air while sliding down the surface to cathc a rope for example

hard viper
#

this isn’t the most uncommon scenario

#

you need to know the effective surface normal

#

getting this by contact points will 100% give you multiple contact points with different normals, and taking the average normal will mess you up

#

other ways to get normals involve other physics queries, like casting

latent latch
#

problem with casting is you still need to know the location you want

hard viper
#

if you cast a shape in a given vector from a given position, you will get a unique RaycastHit3D, and it will give a unique normal

hard viper
#

Cast to get normal for something with which you are not in contact.

rocky jackal
#

the location of the contact ?

hard viper
#

you need to know the start pos and desired end pos, so you can cast from start with a displacement vector

latent latch
#

right, because you may have made contact at different points

hard viper
#

and you WILL make contact at different points

#

it WILL happen, and you must be ready for it

#

Collider2D.Distance has an equiv 3D method that I think is called CalculatePenetration or something

#

if two things are in contact, it will give the smallest vector that you need to separate them