#archived-code-general

1 messages Β· Page 292 of 1

signal moon
#

ok, ill do it in the moment

#

!code

tawny elkBOT
signal moon
tardy moss
#

How do I merge a main with a building inside it so I can enter the building (both have collider along with the player controller) + remove the larger mesh parts where both meets ?

#

Is this something that is done with colliders/mesh filters settings or it has to be done by code ?

#

Tried to find unity learning mesh merging unity learning mesh overlap but couldnt find anything 😦

lean sail
ashen yoke
#

main entrance?

signal moon
#

Im sure the problem is in unity as it works well on autors project

heady iris
#

no, the problem is in your project.

#

If CardContainer isn't attached to an object with a RectTransform on it, then rectTransform will be null

signal moon
tardy moss
# ashen yoke what do you mean by "a main with a building"?

I have a free terrain that is a glTF I dont have access to the original mesh. It's not a unity terrain just a mesh with a collider I use to walk on. I want to put an underground cave throught one of the mountain on it but I cant enter it because the mountain block me and the mountain render over the entrance

#

everything else work except I cant enter the cave

#

cuz my controller collider collide with the terrain collider over it

heady iris
#

what about CardWrapper?

#

looks like that's the oen that's producing the error

ashen yoke
signal moon
ashen yoke
#

unity terrain supports making holes in a similar fashion afaik

heady iris
tardy moss
#

Im not sure how to convert the mesh to terrain either, I mean the mesh came with its own terrain textures I dont want unity to use its own terrain texture...

signal moon
ashen yoke
#

yeah so im suggesting either writing a tool that removes tris yourself, or find it, or edit the mesh in any 3d package

tardy moss
heady iris
#

You could log a warning in the Awake method of CardWrapper to see if any instances are unable to find a rect transform.

heady iris
#

That object does not have a CardWrapper on it.

signal moon
#

yes, bcs it is assigned in playtime

heady iris
#

Does clicking the first error highlight an object in the hierarchy?

#

You'll need to do that while the game is running

signal moon
mossy snow
heady iris
#

Oh!

#

Yes, I completely blanked on that

#

Awake runs once the object is activated

#

(the component can still be disabled)

signal moon
#

actually it has them active

heady iris
#

log something in the Awake method to make sure it's actually running

#

you can also log the resulting value of rectTransform

signal moon
#

XDDDDD

#

thank you

heady iris
#

when in doubt, sanity check it with a log

signal moon
#

The problem was that i didnt actually know what to log

#

like i forgot the difference between start and awake

arctic plume
#

Does the renderer for a child object not get disabled if the renderer for the parent object is?

ashen yoke
#

no theres is no connection

arctic plume
#

Ok thank you

glad plinth
#

Is there a way to make it so i dont have to manually add each Element as its not just going to be one canvas layout but multiple for multiple games so itll be quite difficult to keep it managed like this

leaden ice
#

If so you can just do this once. Make a prefab and reuse it.

#

You can also use prefab variants

#

as for things like PlayerX_Op - you can use an array, or just reference their parent object and iterate over them in code as needed.

glad plinth
heady iris
#

I'm evaluating a spline's up-vector about 120 times per frame. It's incredibly slow -- I turned on Deep Profile, so this is exaggerated, but it's still doing an enormous amount of work.

Asking for the position and tangent is significantly less expensive. I have no idea why calculating the up vector is so particularly bad here.

#

I guess this is some kind of iterative process, but still, holy cow

#

I'm using the spline to position and rotate about ten transforms, and I had 12 instances of that thing in the scene here

ashen yoke
#

is that inside a job?

heady iris
#

No, it's run straight from managed code.

ashen yoke
#

back then i did tests and math lib was slower outside jobs than MathF

#

(quite a while ago)

heady iris
#

I just switched to using splineContainer.Evaluate instead of working on the spline directly, and instead of calling the three Evaluate* methods separately

#
if (splineContainer.Evaluate(splineTime, out var pos, out var tan, out var up))
{
    item.position = pos;
    item.rotation = Quaternion.LookRotation(tan, up) * offset;
}
#

roughly the same behavior

#

I didn't realize until now that you could burst this, so I'll give that a try

#

i'm just startled by how quickly this ground to a halt

ashen yoke
#

did you enable release mode?

heady iris
#

release mode for what?

ashen yoke
#

for the editor to see if any optimizations kick in

heady iris
#

oh, rather than being in debug mode

#

it's in release mode

#

also, hm you can't just throw an entire Spline into a bursted method

#

ah, you have to allocate a NativeSpline

ionic adder
#

Anyone know if methods that use a [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)] attribute run on the main thread? Or would there be a way to somehow to test that?

heady iris
#

I sure hope it does

#

my game controller wakes up with a RuntimeInitializeOnLoad method

quartz folio
heady iris
#

I'm guessing it'll be a lot happier if I don't do that

rigid island
quartz folio
#

There might be a form of evaluation that doesn't rebuild the cache

#

Because the cache is useless if you're constantly rebuilding it

heady iris
#

ah, it pre-calculates a bunch of vectors, then?

ionic adder
heady iris
#

I wrote a script that "parents" each bezier knot to a Transform

#

so that the curve follows the transforms around

rigid island
autumn field
#

I'm working on a package that has some shaders. The shaders are not referenced by any materials since material instances are created at runtime by my code. This causes the shaders to be stripped from builds.

This package will be used in multiple projects and I don't to manually add the shaders to the Always Included Shaders list in the Project Settings. Is there a way to automatically ensure the shaders are included in builds?

I could generate a scriptable object that references the shaders and then reference the scriptable object from a something included in builds, or write a script that adds the shaders to include list automatically, but that all seems silly to have to do.

I also saw there was a [ShaderIncludePath] attribute, but it's obsolete :/

Is there a good way to automate including shaders in builds?

heady iris
#

30 of them per knot

#

It looks like ISpline has a separate CalculateUpVector method that says it's "slow, but more precise"

#

and it looks like it doesn't interpolate between a pre-calculated array in the implementation

thick terrace
autumn field
#

One solution I just thought of was to put the shaders in a Resources folder since resources are always included.

heady iris
#

gonna have to mess with Cinemachine a little to make its spline cart use the slower (and thus, faster) method

late lion
late lion
heady iris
#

yeah, I lean towards Resources when it's something that'd be completely pointless to do by hand

late lion
#

You can also create a IPreprocessShaders build processor to conditionally strip the shaders, if you have some way to detect whether they are actually needed.

heady iris
#

every kind of "module" in my game (a MonoBehaviour that is attached to a specific entity (no, not the DOTS kind)) has an associated ModuleInfo scriptable object

#

it contains a name and description

#

the module just yanks the object out of Resources whenever it's needed (the name matches the module's class name)

#

this way, i can actually serialize the LocalizedStrings correctly

#

I wish Unity had a way to serialize static references to assets in the inspector.

vivid remnant
#

Can you access the methods within a script if that script is disabled?

heady iris
#

Being disabled or even destroyed has no bearing on your MonoBehaviour class's code.

#

A disabled MonoBehaviour instance simply doesn't have a few messages sent to it (like Update and FixedUpdate)

#

A destroyed MonoBehaviour's code still works just fine. You just can't ask Unity for anything (like the transform of the object you're attached to)

vivid remnant
#

I built an interaction system that includes buttons that the player can press in order to open doors, make platforms move, etc.

#

So far I managed to implement simple buttons. You press them and they do their thing.

#

Now I'm trying to make buttons that you can only press once. If you try to press them again after that, they won't do anything.

vivid remnant
heady iris
#

A bool field is exactly how I'd implement that.

#

I guess the button component could destroy itself, but that sounds a lot more annoying to work with

vivid remnant
#

I see where you're coming from but to me, it seems like I'm making the computer perform needless work by using a flag. It's as if I'm making it check for a condition that I'm aware will never again be satisfied.

heady iris
#

This is an extremely tiny micro-optimization to be worried about

#

don't even think about it.

#

just write code that's easy to understand and easy to extend

vivid remnant
#

I tried using the Destroy method right now and it works fine. :)))

#

Thank you for taking the time to help me out.

heady iris
#

sure, and what happens if you decide to put a tooltip that hovers over the button to tell you that it's disabled? now the tooltip breaks, because the button component is completely gone

#

I would destroy the component if the thing the component represents was completely gone

#

it's not gone; it's merely no longer usable

vivid remnant
#

To be honest, I never thought of that. I was planning to only show a tooltip if the object could be interacted with.

#

But I think it's better to listen to your advice.

#

I'll just use an if statement.

#

Better than to give myself extra headaches in the future.

cinder spruce
#

Does EnableKeywprd only work at runtime and not within editor scripts ?

rugged sail
#

how can I invoke a method that has parameters?

latent latch
#

If you need to pass parameters to your method, consider using Coroutine instead. Coroutines also provide better performance.

rugged sail
#

alr thx

vale bridge
#

is it not possible to call a function of a scriptable object from an inputActions callback?

#

It tells me that I'm not setting the reference to an instance of an object so I imagine it had something to do with the SO

#

nvm I figured it out

#

turns out I was setting up the return value of a void function to a callback, when in reality I needed to hook up the function itself to the callback subscribe

tardy moss
#

do I get a role here when Ive gone throught unity learning so you dont give me the bot command to check out unity learning ?

tardy moss
#

love it when a github unity example has a file called ActuallyTrying.cs like they were going to say on discord : "Im actually trying and dont understand here is the filename and class to prove it"

latent latch
#

you get a gold star in my book

random oak
#

trying to make my own slider but I'm still confused on clamping.
I have it follow mouse fine. How to keep the blue between the two orange lines ?

    public void OnDragging(Vector3 mousePos)
    {
        var pos = transform.position;
        pos.x = mousePos.x;
        transform.position = pos;
    }```
fleet gorge
#

is this on canvas layer?

random oak
fleet gorge
#

assuming that your slider is vertical and not rotated, you can transform.position = new Vector3(transform.position.x, Mathf.Clamp(transform.position.y, min, max), transform.position.z)

random oak
#

I tried cs private void Awake() { initPos = transform.position; } public void OnDragging(Vector3 mousePos) { var pos2 = transform.position; pos2.x = Mathf.Clamp(mousePos.x, initPos.x + 0.2f, initPos.x - 0.2f); transform.position = pos2; }
Did not work

fleet gorge
#

if its in world space you need to screentowroldspace it first

fleet gorge
random oak
fleet gorge
#

oh

#

wait nvm

#

when it goes out of the orange lines does it stay outside until you release the mouse?

random oak
#

It keeps following mouse on its x axis

fleet gorge
#

but does it snap back into place after you release the mouse?

random oak
#

snap back? I'm not sure what you mean

quaint rock
#

so if that is vertical why is the code all about the x axis

random oak
quaint rock
#

ok, and this is on what like a overlay canvas?

#

since there is no transformation of the mouse coords (screenspace) to world coords

random oak
#

just regular object with collider

quaint rock
#

also add some logging, see what values you are getting for transform.positon as you apply it

quaint rock
#

well you would want value, min then max as args but yeah should work

#

but like i said Debug.log

#

see if your expected range is just wrong or and what the actual numbers are

random oak
latent latch
#

So, here's a question. Say I want to linecast to check if a certain target is in line of sight, but I want to filter out other similar targets that may be obstructing the line, but if I do that then technically I'd be filtering out the main target's layer too.

#

Is the idea to swap the main target's layer/tag just for that line cast then swap it back? Haha

#

Perhaps a dedicated layer "LineOfSight" that I flip on every target I check against, or will I run into issues with this idea? (I'd assume swapping layer is instantaneous and there shouldn't be any lingering problems if it's all executed together)

fair jackal
#

After the linecast, maybe you can check for other things like script? (Unless it’s just a regular object with no special components)

lilac bobcat
#

Quick question, if I have a class which contains a number of unity properties and a multidimensional array of objects and I wanted to convert it to a JSON file for saving and loading, what would be the best way to go about it?

tardy moss
#

Json.Serialize(obj); super easy one liner, newtonsoft.json from unity enterprises it is a static method

#

you can add settings to the call/use JsonSerialize<> constructor after that if it doesn't do exactly what you want

lilac bobcat
#

Can newtonsoft support serializing things like Vector3 and Quaternion?

tardy moss
#

keep in mind unity limitation that it doesnt serialize private members/properties etc by default

#

try ? it takes like 5 seconds

#

I see no reason why it wouldnt besides the unity limitations I mentionned, serializer serialize every members by default

tardy moss
#

why use random newtonsoft packages rather than the official one in the package manager window though ?

somber nacelle
#

because versions before 3.0 did not support those types out of the box

#

which is clearly mentioned in the readme there

#

this is also not a replacement for the newtonsoft package, this is for use in addition to it
also unity's implementation is based on this one

quartz folio
#

It's very much not a random package πŸ˜„

lilac bobcat
somber nacelle
#

just note that if you are using unity's fork then you shouldn't need that

latent latch
#
void RicochetAbility()
{
    Vector3 normal = (currentHitTarget.ClosestPoint(transform.position) - transform.position).normalized;
    Vector3 reflectionDirection = Vector3.Reflect(transform.forward, normal);
    hitRotation = Quaternion.LookRotation(reflectionDirection, Vector3.up);
}

This kinda works, but I'm having issues that if projectile hits a wall dead-on, it'll continue going straight through it. Any ideas?

latent latch
#

nudging positions a bit does seem to help, but the reflection direction has become unpredictable a bit.

#

blah guess ill just use OnCollision, or maybe just raycast it

#
void RicochetAbility()
{
    Vector3 collisionPoint = currentHitTarget.ClosestPoint(transform.position);
    Vector3 normal = (transform.position - collisionPoint).normalized;
    
    if(normal == Vector3.zero)
    {
        hitRotation = Quaternion.LookRotation(-transform.forward, Vector3.up);
    }

    else
    {
        Vector3 reflectionDirection = Vector3.Reflect(transform.forward, normal);
        hitRotation = Quaternion.LookRotation(reflectionDirection, Vector3.up);
    }
}

Actually that seems to be an ok bandaid for now

#

the normal zeroes out sometimes cause I guess the contact and position or too close, but the problem with nudging positions is like in what direction do I nudge if say the sides of the collider made contact first

#

so if anyone has any ideas for that

lean sail
# latent latch so if anyone has any ideas for that

how are you getting the currentHitTarget currently? with raycast maybe just use the normal given from there. One case u might be getting weird functionality is because when they collide, the 2 objects might be overlapping slightly, and the transform position is being taken inside the collider

latent latch
#

I'm getting it from OnTriggerEnter, but yeah it's probably cause it's all overlapping

lean sail
#

oh yea OnTriggerEnter would be worse for that since it wouldnt stop objects from moving

latent latch
#

even with raycast im not sure that would help. I would think a second collider maybe

lean sail
#

its the normal of the surface hit

latent latch
#

thing is, im not too sure where I would target with the raycast if not the collisional point

#

oh, you mean instead of using the collider entirely

#

I kinda just actually swapped over to colliders. Was using overlap for a bit but I've gotten to the point where kinematic controller will work with what I got.

dim forge
#

Im working on generating a dungeon, and the algorithm places rooms as it goes, however, i need to check for room collisions when placing them. Preferably, i would like to do this before i Instantiate the room. Is there any way to get some bounding box information of a GameObject?

delicate flax
dim forge
#

oh, interesting, ill see what i can do with it, thanks!

woeful narwhal
#

this is a text wavey effect for text mesh pro. does anyone know any other cool ones _verts[_charInfo.vertexIndex + j] = _original + new Vector3(0, Mathf.Sin(Time.time * 4f + _original.x * 0.01f) * 10f, 0);

rocky osprey
#

is there an equivalent to Task.FromResult<T> for Awaitable<T>?

thick terrace
#

i think you have to make a completion source and set the result, which isn't quite as bad as it sounds (awaitables are pooled so it's probably still only one allocation?)

rocky osprey
#

cool, that did it. thanks!

thick terrace
#

i can see myself writing a helper method to do that whenever i get around to upgrading to awaitables πŸ˜… i wonder why they didn't include an easier way

#

i guess if you're frequently returning values with Task.FromResult it's worth considering using ValueTask instead of Awaitable anyway

crystal knot
#

I'm having an issue with the circle where it bounces back and forth rapidly.

#

this is the corrosponding code. using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball_Movement : MonoBehaviour
{
private Rigidbody2D rb;

float t = 0.0f;
public float x = 0.0f;
public float y = 0.0f;

// Start is called before the first frame update
void Start()
{
    rb = GetComponent<Rigidbody2D>();
}
void OnCollisionEnter2D(Collision2D Paddle)
{
    rb.gravityScale = 0;
    y = 3.0f;
    Vector2 vel = new Vector2 (x, y);
    rb.velocity = vel; 
}
void OnCollisionExit2D(Collision2D Top_Border)
{
    y = -3.0f;
    Vector2 vel = new Vector2 (x, y);
    rb.velocity = vel;
}

}

static matrix
#

is it possible to make an optional out?

leaden ice
static matrix
#

THE USECASE IS FOUND
great

leaden ice
#

Or do you mean with a default value?

Ref would just not require the function to write it, if that's what you mean

static matrix
#

thats what I mean

crystal knot
sleek cliff
#

Guys I want some information whenever I download unity install editor it's get failed I have rtx 4060 laptop why is this happening

leaden ice
sleek cliff
#

Ok

#

Brother

#

But I am getting this problem bro

static matrix
#

yeah I may be overcomplicating things
I was trying to rewrite my FindClosest method, which returns a vector3, to also optionally be able to return the object its attached to
when I should just write a FindClosestObject method

sleek cliff
#

Huh

#

Heloo

static matrix
#

patience, young one

sleek cliff
#

Ik brother

#

Ok

static matrix
#

you also asked basically the most vague question known to man
"I download editor it no work plz explain"

sleek cliff
#

I install 2021 unity editor it's getting failed

vagrant blade
#

Move this conversation to #πŸ’»β”ƒunity-talk where it belongs and where you've already asked @sleek cliff. You don't need to tak eup three channels.

#

Nor is it a programming question.

static matrix
#

alright

sleek cliff
#

Ok brother osteel

tardy crypt
#

Is there any reason I shouldn't use a static class with static functions for pure functions that are just library functions?

thick terrace
#

no, that's a good usage

tardy crypt
#

ok thanks

rocky osprey
#

in case anyone wants to do that public static Awaitable<T> FromResult<T>(T value) { var completionSource = new AwaitableCompletionSource<T>(); completionSource.SetResult(value); return completionSource.Awaitable; }

mystic gull
#
    private float _hitTime;
    [ContextMenu("Hit Animation")]
    private void OnHit() => _hitTime = Time.time;

ContextMenu doest not change the _hitTime value. This attribute only for Debug purposes?

leaden ice
mystic gull
#

All I want is just set the value by calling Hit Animation ContextMenu function

#

And why it has to be serialized?

static matrix
#

is it possible for me to quickly add code to all instances of an abstract function (vscode)

dim forge
mystic gull
#

Duplicated.
I want to create the AnimationPlayer MonoBehaviour class for animation purposes. I want to run methods of the class asynchronously. What concepts should I use: Async/Await, Tasking, Threading, Coroutines?
Target platform is mobile

weary dawn
#

I want to instantiate a gameobject after a gameobject ie. I want it to be a sibling. How do i do it?

leaden ice
#

(make it a child of the same parent)

weary dawn
#

forgot to add. Lets say there are 4 child in the parent right. I want it to be the second one (index 1) when instantiated

cinder spruce
#

Do you guys know what can be caausing this :
Objects are trying to be loaded during a domain backup. This is not allowed as it will lead to undefined behaviour!

When i create a new project and create a shadergraph, after a few minutes i start gettting this eerror. And once its there you keep getting it more and more until editor restart

#

I tried on the 2023 something version and again on the 6.0 one

vagrant blade
long hare
#

alright

spice briar
#

hey everyone, so im trying to make an ArmA-style zoom, where you can press right mouse to toggle aim down sights, but if you hold the button down for half a second it zooms the camera in

#

does anyone know how to set this up using the new input manager?

heady iris
#

You can use an Interaction to create an action that's only performed once the button has been held for long enough.

spice briar
#

yeah, but the problem with that is that the normal aim down sights also gets toggled when i hold down the button

#

i want aim down sights to not go if i hold the button down

heady iris
#

Add a "Tap" interaction to the aim-down-sights action .

#

Tap requires you to press and release the button quickly

spice briar
cyan hornet
#

I closed my visual studio and opened it again

#

and viasfora was still not installed

#

does anyone know how to fix this?

heady iris
#

It's possible that something is stuck in the background. I'd restart my computer and try again.

dim forge
#

How can i tell if a collider is currently in collision with another collider?
I have a class that generates rooms of a dungeon. The idea is that every time i Instantiate a room, i run a check if it collides with any other room and if yes, it gets destroyed and replaced.

#

I thought i could just use the "OnTriggerEnter" but the problem is that my script is just on some empty object that has nothing to do with anything. Do i have to create a new script, place it on the rooms, and then read collision data from this script?

thin aurora
#

Though I can't find what it is called

dim forge
#

yeah i can't find anything like this in the documentation

thin aurora
#

Could have sworn I used it before

thin aurora
#

This accepts an array and it will fill the array with all the touching colliders

#

But I can only find this for 2d colission

dapper fern
#

I've got a general question about Singletons and "Managers".

Let's say I have several 'manager' type scripts in my scene. Each one of them exists in a single instance, so it makes sense to make them a singleton. The thing is, they have methods and events I want to invoke from different places throughout the game, so for example I may have 64 objects that refer to something from that manager several times per a game session.

It makes sense to cache the reference to a manager, but, obviously, I can't make a [serializedfield] on 64+ objects and drag the manager there. Not caching and calling Manager.Instance to get the singleton every time would not be ideal as well, cause I know that's much less efficient than caching it somewhere. I can't cache reference to this singleton during object's Start() or Awake() because, obviously, singleton may get initialized AFTER the object that tries to cache it.

I've read about Lazy Initialization of singletons and also I've read about using callbacks to cache this singleton into the object only AFTER the singleton is initialized, but I'm not sure that will work either.

Basically, I'm asking what is the standard, non-stupid way to handle Singleton caching, initialization, subscription, etcetera( when calling Manager.Instance over and over during runtime isn't viable)?

dim forge
thin aurora
#

The idea is that you give a large enough array for everything to fit in, because this saves on allocation

#

The reason is that this method is likely called very often so this increases performance

dim forge
#

ohhh, so it goes over all the stuff in the scene and whatever is colliding, it returns?

thin aurora
#

You can also give it an empty List rather than an array. Unity will resize it for you then in case you don't know the size it should have

thin aurora
cyan hornet
thin aurora
dim forge
thin aurora
#

No, it already returns all colliding colliders

dim forge
#

yeah alright, thanks a lot

clever trellis
#

I'm have to make logic for possible legal moves for chess pieces.
Currently I've made the logic in one file only and assigned that script to every chess piece. I've been told to follow good coding practice and write clean code.

Now, im confused should i keep it as it is only (every logic in 1 file) as its easier to assign one file to any piece and there's no issue of wrong file assigned.
Or
Second, i should put different logics in different scripts and assign it to individual pieces as per their names (like a rook script for rook, a queen script for queen.... And so on)
Or
Third, i should make different scripts for each individual pieces but connect them through one common script, that will call these scripts after a series of if statements using tags. This way also I'll have to assign only 1 script to all pieces.

What should be the best practice?

lean sail
dapper fern
light wraith
#

is it possible to see custom classes in the editor: but that inherit from a custom class?
for example in my mono behaviour script I have:

IBaseClass myClass;

for example in start:
myClass = new InheritingClass;

how would I edit public fields of myClass from the editor?

#

for debug only.

lean sail
# clever trellis I'm have to make logic for possible legal moves for chess pieces. Currently I've...

Architecture for a game like chess can be really simple if you want to make it only in line with the existing rules. it's really quite easy to just place all your logic in 1 file, give each Piece an enum saying which piece it is, then doing some logic based on that. But if you want clean code, this isnt easy to extend. For example if you wanted to introduce a new piece, suddenly you have to edit this script again. If a piece suddenly changes movement, you need to edit the script again. This script would essentially never be complete. In terms of clean architecture, I'd say it's pretty sufficient to have a base Piece abstract class (or make this an interface but dragging in inspector will require custom editor functionality), then you create child classes which implement methods like how it can move given a certain board.

light wraith
#

I made both the inheriting class and the base class serializable

rigid island
#

iirc you need the attribute

lean sail
#

That's not the issue, you declared the type as the base class

light wraith
#

yea

lean sail
#

Thus you only have access to stuff on the base class

light wraith
#

am I missing something

quaint rock
#

the only way to do this is fairly round about and will need a custom editor

#

but its possible with SerializeReference

latent latch
#

Abstract?

light wraith
quaint rock
#

SerializeReference fully supports polymorphism unlike SerializeField

#

but you will not get automatic creation from the editor so will need to handle that via editor script

light wraith
quaint rock
#

it even supports interface types

#

but you editor logic will need to create the objects yourself

latent latch
#

There's packages around to help for that

rigid island
#

oh ye thats the attribute, forgot the name

light wraith
quaint rock
light wraith
#

ok it seems to work, but whenever I enter play mode it entirely disappears

tardy moss
# clever trellis I'm have to make logic for possible legal moves for chess pieces. Currently I've...

Clean code isn't universal it's just an opinion and if you ask 100 programmers they would differ on a certain practice and there is wisdom in knowing when to use it or not. Seems overengineering in your case but if you insist the way Id do it is define the types of chess pieces and have some sort of IChessPiece they all inherit from so someone else can understand what it does without looking at the implementation just the interface. Especially if you have a epic supermethod with hundreds of if or cases. This mindset is very similar to the book code complete 1/2 about clean code from microsoft, where the authors considered exceptions to every rule they state

latent latch
#

Ive found mackysofts serialize references pretty good and I think vertx had something worthwhile

tardy moss
#

the interface would enable dependency injection as well and testing outside of unity if that is easier for me (sometimes is for me especially when importing new assets and waiting hours, I can just test the code in a winforms project while unity does whatever/mine bitcoins...)

latent latch
#

But in the end I just dont serialize by abstractions even though interfaces is probably a real miss for unity not developing more fore

quaint rock
#

i just wish you could drag in UnityEngine.Objects via interface types, with out of the box unity

light wraith
#

at first it appears in the editor empty

#

on playmode it just entirely disappears

quaint rock
tardy moss
#

speaking of which how do you manage it when you have an itemcollection with items but some asset wants you to fill their catalog with their own item class ?

#

flywheel or interface pattern ?

quaint rock
#

this is a MB or a SO or something

tardy moss
#

or you could delete the class of yours and start over ?

quaint rock
#

SerializeReference is more for regular C# classes @light wraith

#

i assumed that was your case

light wraith
#

not monobehaviour at all

#

I hold a regular C# class as a variable on a monobehaviour class.
I would like to edit values on that regular class from the inspector

#

usually it is possible with just placing [System.Serializable] on the class

#

but in this case, I have an [SerializeReference] IMyBaseClass (= new MyInheritingClass)

quaint rock
#

so with SerializeReference it will show up totally blank first

#

you need to construct the object via code first

light wraith
#

yes

quaint rock
#

then you can see it in the inspector

light wraith
#

in the mono behaviour class:

#

and on start()

#

this is movement state

#

and normal state:

quaint rock
#

strange

light wraith
#

yea

quaint rock
#

quick little test

#

that is a interface type

light wraith
#

mine is abstract but in the docs it says it supports

quaint rock
#

is all i did, then i ran the context menu thing to create the data

light wraith
quaint rock
#

then i was able to edit in the inspector and have it show up as changes in diff

light wraith
#

ok, I will try with your example

quaint rock
#

you will notice in your diffs in git, it shows up very differently then a regular serilize field

#

will warn this approach is fragile to type name changes and refactoring

dim forge
#

@thin aurora I'm still having troubles implementing that GetContacts method, where do i get the collision from?

quaint rock
light wraith
#

@quaint rock am I doing it right?

#

it does show up in inspector all the time, but empty, float test does not appear.

quaint rock
#

even after start?

light wraith
#

yea

#

the screenshot is from play mode

quaint rock
#

toss [ContextMenu] on so you can invoke it in the editor

#

the example i gave was just a quick and dirty test, but how it showing right away for me

#

normally in cases like this when its done i will create a popup menu in the edtior scripting that creates the object of the right type and stores it in my base type or interface type

dim forge
quaint rock
#

with my bounding boxes

light wraith
quaint rock
light wraith
#

what is going on

dim forge
light wraith
#

I added it to ok() and it now works πŸ˜‚

#

I am so confused!

#

but it doesn't even show the function

rigid island
light wraith
#

I can edit the value through the inspector

thin aurora
#

The method collects all active colliders colliding with the calling collider component you call GetContacts from

#

All you need to do is pass an empty array or list and it will fill with references to the other collider components

#

Note in the case of an array you need it to be big enough. If you have a size of 10 it returns 10 max, or less. A list will be resized so that might be better.

knotty sun
dim forge
#

yeah i get that much, i just dont know where to get the collision to call from

thin aurora
thin aurora
#

What is it exactly you want to know in this case?

quaint rock
dim forge
#

like how do i take an object with a MeshCollider and and it "is this mesh collider currently colliding with something?"

thin aurora
#

You would take the object with the MeshCollider and call GetContacts

#

And if I read the wiki correct it should returns a collection of references to whatever the mesh collider is colliding with

knotty sun
#

Collider does not have a GetContacts method

thin aurora
#

Or do what Passerby mentioned, that works the same basically

#

.... The page is about a collision, not a collider

#

Well then

dim forge
#

yeah, thats what i was having trouble with

thin aurora
#

I guess I totally misread this then, I thought it mentioned a collider

thin aurora
#

Actually, it does mention a collider

#

Why is this different? πŸ€”

rigid island
#

box2D vs physx

thin aurora
#

Yeah so the 3d variant is actually completely different

#

My bad

rigid island
#

yeah messes me up sometimes, some features are not available in the other n vice versa

dim forge
quaint rock
latent latch
#

There's contactpoints

#

Which you dont need collision

#

Oh no im think of closest point

#

Was using it earlier for some ricochet logic without a rb

icy herald
#

WHY DOES ANY UNITY METHODS like awake, update MAY STOP WORKING ON ALL UNITY EDITOR VERSIONS?
a

lean sail
quaint rock
#

Awake and Update not awake and update

dim forge
latent latch
#

Rb is for collisions

quaint rock
dim forge
#

Rb?

quaint rock
#

assumed it was just about finding what rooms are overlapped

#

so you can remove them

latent latch
#

Otherwise you need to calculate the first point of contact

dim forge
latent latch
#

Overlap sphere is the answer

dim forge
#

can that find collisions?

latent latch
#

It finds colliders

dim forge
#

but i have colliders, i need collisions

spring creek
#

Colliders that overlap with the sphere

#

Aka, a type of collision

quaint rock
#

if you just need to know hte objects what i posted is enough

dim forge
#

i have the objects

quaint rock
#

if you need each contact point then you would need a collider to create collsion events with

dim forge
#

i need collisions

latent latch
#

You check colliders. Collisional stuff is more specific to rigidbodies

quaint rock
#

what do you need the collisions for?

#

i feel like we have not heard the whole extent of what you want to accomplish

dim forge
#

lets say i want a tree like structure out of rooms, when i spawn a room, i need to check that this new room doesnt overlap with any other room, if it does, remove it and try again

#

every new room is spawned from a door on a previous room

quaint rock
#

so i assumed you wanted to check a volume of space

#

if you want to do it via colliders you already got i would loop through all of those colliders and work with them methods on them

dim forge
#

if i spawn a new room somewhere around these 3 rooms i need it to not overlap the other ones

quaint rock
#

or do like bounding box checks via the OverlapBox

#

which will tell you if other colliders overlap a space

dim forge
#

yeah but the problem is, my rooms arent just squares

quaint rock
#

what type of colldiers are used

dim forge
dim forge
quaint rock
#

so without first spawning things this will be hard to check for

#

what i would do would be looping through the colldiers to get the bounding box for each one

#

then use overlap methods

dim forge
#

yeah but my problem with the bounding box is that, well its a box

#

so it takes the spaces around the room that could possibly be used

quaint rock
#

but in reality are you describing a complex shape like that as 1 collider

#

or would that be 2 or more

dim forge
#

every room is a single object

quaint rock
#

thus you can check that one by one

dim forge
#

how do you mean?

quaint rock
#

so that is really ineffecient since you have 1 massive non convex collider per room?

rigid island
#

I already see that room can be 2 Rectangle colliders

dim forge
#

i mean the rooms are created out of 3x3m prefabs technically

quaint rock
#

like i have done similar feature before in a game i am currently working on

#

but it works since each wall is a collider, each rectangle part of the floor is a collider etc

#

since colliders work best as convex shapes, and i tend to not model 1 room whole sale but build it from modular parts

#

and sometimes even the modular parts have a few colliders if they need to describe a shape like a arch so i can have multiple convex wedge shapes instead of 1 concave arch

#

some of the reason i approach it this way is for the scripting side, and some of it is simple for optimization and workflow and wanting to stay convex everywhere

dim forge
#

okay so lets say each room would be made out of the 3x3m tiles, how would i go about this then?

latent latch
dim forge
#

i might just do that, how would i then check collisions of bounding boxes?

#

just get center, calculate top left and bottom right corner and check with all the other bounding boxes? Or is there some smarter way to go about it

latent latch
#

Though you can always use more than one box. I assume these are prefabs anyway so customize the bounds

dim forge
#

how do i do that? I looked to see if objects have a bounding box component, but i couldnt see one

knotty sun
#

Renderers have a bounds property

quaint rock
#

colliders have them too

dim forge
#

yeah i noticed that in scripting, cant see it in Unity though

quaint rock
#

in the case of tile based games, i have also just in a other object just defined waht shape something is manually on the grid so i could use that to check if its going to overlap anything

#

like there are so many ways to do this

dim forge
#

thing is, this isnt supposed to be on a grid

quaint rock
#

i was just saying that is a other way based on the usecase

dim forge
#

yeah, alright

#

think I'll just create my own Bounds class that works well with my other classes and give up on the idea that the bounds aren't just rectangular

somber tapir
#

Playing Videos in a WebGL build seems to no longer be working. I tried the VideoPlayer approach with the video file being in the StreamingAssets folder. It works in the editor but in a WebGL build only the sound plays, the video stays black.
Anybody here have an idea why that is?

videoPlayer.errorReceived += VideoPlayer_errorReceived;
string streamingPath = System.IO.Path.Combine(Application.streamingAssetsPath, path);
errorText.text = streamingPath;
videoPlayer.url = streamingPath;
videoPlayer.Play();
```I get no errors either.
modern creek
#

I've got this effect for when a player touches the screen - I emit particles from the touch location. I move it around and set the emission rate to 100/0 depending on if the player is touching the screen. Works great except when they first touch - it plays a particle or two from the last location of the game object.

I'm definitely moving the object before setting the emission rate to 100 but I imagine that because it's in the same frame, it can emit a particle at the old location.

Any ideas how I can get partcles to not emit for one frame easily?

#

(sometimes there's one particle emitted from the wrong place)

hard viper
#

i feel like i’ve had this issue before, but I don’t recall the answer. did you try making sure the particle effect gameobject is in the right position before turning it on?

#

or is it not on a gameobject at the cursor?

modern creek
#

so... i'm not actually turning the GO on/off, just setting the emission rate.. because i want particles to live after the emitter stops

#

lemme paste some code, sec

hard viper
#

i think i normally use a trigger event in the vfx

modern creek
#
        private void StartTouchParticles()
        {
            ParticleSystem.EmissionModule em = TouchParticles.emission;
            em.rateOverTime = 100;
        }

        private void StopTouchParticles()
        {
            ParticleSystem.EmissionModule em = TouchParticles.emission;
            em.rateOverTime = 0;
        }
        public void OnDrag(PointerEventData eventData)
        {
            if (!_isDragging) return;
            TouchParticles.transform.position = eventData.position;
        }
        public void OnPointerUp(PointerEventData eventData)
        {
            StopTouchParticles();
            if (!_isDragging) return;
        }
        public void OnPointerDown(PointerEventData eventData)
        {
            TouchParticles.transform.position = eventData.position;
            StartTouchParticles();
        }
#

that should be all the relevant stuff

hard viper
#

look at the VFX graph

modern creek
#

but the position is set in OPDown before it starts emitting

#

the vfx graph...?

hard viper
#

how are you making your particles?

modern creek
#

just a vanilla particlesystem

hard viper
#

do you not have a VFX graph?

modern creek
#

Unity.ParticleSystem or whatever

#

i mean, I have a library that's flattening the particles into UI meshes but that should be irrelevant for this

#

.... maybe

hard viper
#

first try turning off play on awake

#

i suspect that might be emitting something, that then gets paused

modern creek
#

shouldn't matter, since the GO is always on

#

like i never call play() stop() or any of the ParticleSystem methods to start/stop the system .. the only thing i do is change the emission rate

hard viper
#

idk much here. but i suspect invoking play/start manually is the way

modern creek
#

i can't recall though - i think stopping the system kills the "in flight" particles

hard viper
#

you are probably right. sorry, i’m not well versed in this one. you will need help from someone else

modern creek
#

all good.. open to any ideas TBH.. can't seem to figure it out, short of making this more complicated than it needs to be with a coroutine that sets the emission rate a few frames later

dapper fern
modern creek
dapper fern
#

Oh? why do they frown on it tho?

modern creek
#
    public class PlayerManager : ReloadableManager
    {
        public static event Action<MinigameDefinition> StartedNewMinigame; // UI subscribes to "domain logic" events and animates them accordingly
        public static int HighestLevelCompleted => Instance._highestLevelCompletedCached; // simple data points, accessible anywhere
        public static void SubtractLife() => Instance.SubtractLifeInternal(); // "global" methods contained within the singleton

// and the boilerplate
        private static PlayerManager instance;
        private static PlayerManager Instance => instance == null ? FindFirstObjectByType<PlayerManager>() : instance;
        private void Awake()
        {
            if (instance != null)
            {
                Destroy(gameObject);
                return;
            }
            instance = this;
            if (_player == null) LoadPlayerInternal();
            _isInitialized = true;
        }
}
#

race conditions, tight coupling, etc

#

I like it because it's convenient - I put all my singletons in a single DDOL in my loading scene, and then all the functionality in my entire app is available without any fussing about instantiating and/or getting references to these game logic objects

#

the bulk of my codebase is rendering/ui anyway

dapper fern
#

it does sound convenient. as I see it, you need non-static events when you need to listen for events from a specific instance of the class, and maybe not listen to another instance? If you don't need that, or if you're gonna have only one instance of this class (if it's a singleton) then... any events fired from it... will be fired from only one place? right?

modern creek
#

i don't have any non-static instances that emit events.. that's just not a pattern i really need

dapper fern
#

so making these events in this scenario non-static only puts a burden on you to subscribe to a specific instance and figure out the script execution order as well

modern creek
#

I use events really heavily since it bridges "domain" and "view" really nicely

leaden ice
#

The fun thing about static events is you can always just manually pass in the source instance if you want as well

modern creek
#

my 99% use case is "something happens that requires UI, so emit an event" and all the UI stuff that cares about it subscribes/unsubs in OnEnable/OnDisable

#

yeah - i haven't needed it (i almost always just send null in the obj sender pattern) but it's there if you do

dapper fern
#

that is absolutely right

leaden ice
#

so the use case for non-static events is really limited to when you need a lot of different listeners listening to a lot of different specific instances of things.

For example if you had 100 enemies each with their own health bars emitting HealthChanged events. You wouldn't want them all to say if (source == theOneICareAbout), you'd just subscribe them each to the appropriate instance event

modern creek
#
    public class GoalUpdatedEventArgs : EventArgs
    {
      // bunch of data
    }
  

public class GameManager
{
  public static event EventHandler<GoalUpdatedEventArgs> GoalUpdated;

  private void SomeMethodThatDoesShit()
  {
     GoalUpdatedEventArgs args = new()
     {
        // blah blah blah
     };
     GoalUpdated?.Invoke(null, args);
  }
}
#

EventHandler.Invoke(object sender, T args)

#

i think you're "not supposed" to use this as the first parameter in static classes but.. if you need to, you can

leaden ice
#

Unsolicited advice - but I recommend not using the EventHandler pattern in Unity

#

Unecessary overhead/GC allocation

modern creek
#

oh? why's that? i was just starting to move to it

#

interesting.. just instead of vanilla delegates?

leaden ice
#

Just define your own delegate type!

public delegate void GoalUpdatedHandler(Enemy source, int myParam1, int myParam2);```
modern creek
#

i've lately been migrating my codebases over to that pattern, I wasn't aware of GC overhead

#

yeah, well, that's close to what I did (I used Action<T> though with a <T> that had all the parameters)

hard viper
#

almost all of my delegates are Actions, so I rarely need to define my own

leaden ice
#

using object source isn't type safe and could involve boxing struct types
And allocating a new MyEventArgs instance is GC allocation if it's a class

hard viper
#

but if you have a delegate used a lot that has non void return type, then defining it is a good idea

leaden ice
modern creek
#

otherwise my delegates started to get hairy and confusing

public static event Action<int, int, float, string, (Color start, Color end)> TileUpgraded;

this is an actual event in my codebase that I haven't migrated to the "new" way yet

leaden ice
#

because I like typing HealthChangedHandler instead of Action<Unit, int, int>, it's more clear

modern creek
#

obviously the big problem here is not having a T to hold all those parameters

leaden ice
hard viper
#

that is exactly the case for named delegates

#

avoids confusion

leaden ice
#

But I recognize the convenience of Action where appropriate

modern creek
#

obviously one is easier to read

leaden ice
#

public static event TileMovedHandler TileMoved;

quaint rock
#

yeah i only use Action for 0 to 2 args

modern creek
#

although I haven't found a good "normal" place to hold event arg classes

quaint rock
#

if its more complicated i will define a proper delegate type

modern creek
#

I kinda hate littering up other files with them, but then they feel too "small" to each have their own file

lean sail
hard viper
#

define a delegate in the scope of a class that uses it a lot

modern creek
#

I've gone back and forth on the struct thing because of the copying overhead.. I mean, I'm using a lot of events in my codebases

quaint rock
#

what do you mean littering

hard viper
quaint rock
#

just put it in the scope its needed

#

only stuff in a class cares about that delegate type make it there

modern creek
#

yeah, I suppose i could put it inside the scope.. didn't htink of that

quaint rock
#

same goes for structs and enums and stuff

lean sail
modern creek
#

ie here's my .. GameManager file, collapsed a bit:

quaint rock
#

i very commonly have a bunch of supporting types defined inside the scope of a larger type

modern creek
#

GoalUpdated, TileDestroyed, TileMoved events are all like... 4 lines.. making a file for each of them seemed silly

#

didn't think to put them inside GameManager

hard viper
quaint rock
#

like one of my SO's has really complex nested data defined in it, i literally have 2 enums and 8 structs defined inside of it and a delegate

#

so those dont litter the whole namespace or assembly

modern creek
clever lagoon
#

Well, this was unexpected! Type 'UnityEngine.Color' in Assembly 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null is not marked as serializable. I'm using BinaryFormatter to create a custom save file. Do I really need to create a whole new custom struct, and populate it at serialize-time just to save a Color?

heady iris
#

Unity's notion of "serializable" is distinct from C#'s notion of "serializable", yeah

#

I'm not sure if there's a way to convince BinaryFormatter that the type is fine to serialize

#

also, you're about to be warned about BinaryFormatter πŸ˜‰

leaden ice
leaden ice
#

Yeah it's formatter

clever lagoon
#

yeah, I mean I CAN create a custom struct marker with [System.Serializable].. just gonna be a pain.

leaden ice
#

You know me so well Fen

heady iris
#

I clicked on the warning on that page and it took me to one written in Spanish

clever lagoon
peak elk
#

hello! i have a question, how can i make a custom editor where i hide and show variables based on the toggle? i've tried to do smth but it didnt really do what it was supposed to lol, also am using custom list's(variables inside lists), should i send the full code here?

leaden ice
#

Anyway I'll drop it πŸ˜‰

spring creek
clever lagoon
#

just a home project. But I AM curious about it ... my game open the file and fills data structs.. how COULD injected code get executed with that?

peak elk
peak elk
#

but the options piece to hide or show the top or bottom variables(bottom being isremu and text_) and true for showing the anwser_options array

clever lagoon
heady iris
#

it can execute completely arbitrary code when it deserializes data

#

BinaryFormatter is more constrained: you cannot trivially make a blob of data that runs completely arbitrary code

heady iris
#

it's pretty cool: it's a lot like building a ROP exploit out of small code gadgets

clever lagoon
autumn lantern
#

hey guys had a question about grids / a* pathfinding. If i'm doing pathfinding jobs, do you guys recommend creating a new grid array for each pathfinding job, to store parent nodes correctly?

or have one master grid?

heady iris
#

it's abusing existing libraries to cause things to happen to your system when you deserialize data

#

extreme example: if you have a class that deletes all of your files when you construct it, then deserializing data that includes an instance of that class will rm rf you

clever lagoon
#

guess I misunderstood "The main driver program takes a user-specified command and wraps it in the user-specified gadget chain, then serializes these objects to stdout." But regardless, this special code/class must already be on the system, right?

heady iris
#

the problem is that the special code is from standard .NET libraries

#

it's not really special at all

#

That's the idea of these "gadget"-based attacks

#

return-oriented programming takes small pieces of code from a vulnerable program and strings them together in a way that winds up making the program do something evil

clever lagoon
heady iris
#

I believe the core problem with BinaryFormatter is that you can't say "I want to deserialize a Widget": it just does whatever the binary data tells it to do.

heady iris
#

I currently just use Json.NET. I've been thinking about switching to BSON (which is roughly just JSON, but with binary data instead of printable characters)

#

Json.NET has a pretty major advantage here too -- you can write custom converters to deal with this kind of thing

#

so when it finds a UnityEngine.Color, you can tell it "oh, just write four floats"

#

You don't actually have to create a "serializable color" type in that case

clever lagoon
#

Will check it out. That system handle references to objects properly? (by which I mean... I have say 4 referencs to an object, will it save it only once and create the appropriate references at deserialize time?

dim forge
#

how can i get OnCollision functions working on objects with Mesh colliders? I dont want to make the mesh collider convex

heady iris
#

However, you can put a rigidbody on something that hits a non-convex mesh collider

dim forge
#

yeah I'm checking room collisions, both of them have mesh colliders. I guess ill just make them convex, check collisions and make them not convex

heady iris
#

More generally, I'm also not really sure -- I've stuck to serializing things like settings, statistics, and configurations so far. Much more tree-like.

#

It's something I am going to have to figure out at some point; it just hasn't happened yet

heady iris
dim forge
heady iris
#

Is this for level generation?

dim forge
#

yeah, checking if a generated room intersects previous rooms

clever lagoon
#

^ note this uses a box that encompasses the entire mesh, meaning 2 L shaped rooms (concave) could have the bounds overlap, even though the meshes themselves might not overlap.

worldly ruin
dim forge
leaden ice
#

Anyway just kinda looks like a particle system with some masking effect

worthy willow
#

I made a script that generates new waypoints if my Ai gets stuck on a wall (the scene is dynamic)

#

at line 143

#

i want to choose the point with the smallest distance, how can i do that

quaint rock
#

keep a var for the minDistance seen and for the object that got it

#

each time something has a smaller distance assign both

#

see what you got at the end of the loop

worldly ruin
weary swift
#

If you saw my question, I just don't know how to read. My problem is fixed !

worldly ruin
naive plinth
#

Hello! I was looking for info on creating a multiplayer game using Netcode for Gameobjects with a mix of ECS for the terrain generation.
However, when I install both, i get an error since there seems to be a conflict with the libraries. Has anyone found a soluition for this?

leaden ice
rigid island
#

ECS is not compatible with GameObjects

naive plinth
#

not possible then?

leaden ice
#

like... to generate the terrain?

naive plinth
leaden ice
#

or what?

naive plinth
#

Yeah, just the terrain

#

the problem isn't using one of the technologies, its more on having both packages NGO and ECS in the same project

rigid island
#

just use DOTS for terrain then

#

you get some benefits by using Jobs for example if you want to split it on different threads

ashen yoke
#

by terrain you mean just the terrain data, or deformations, objects on it?

naive plinth
#

mainly data. including deformation intention

#

objects would be normal game objects

ashen yoke
#

if just data you can run generation in jobs, no ECS needed, but i think that even if you need ECS you can keep ECS world and copy entity data to the GO world

naive plinth
#

alright, ill focus on the DOTS aspect instead of ECS. Thanks @ashen yoke @rigid island

rigid island
#

but yeah I'd learn Jobs first

naive plinth
heady iris
#

Yep! I use Jobs in games that aren't Entities-based at all.

#

combined with Burst, you can do a lot of work very quickly

autumn lantern
ashen yoke
#

what do you mean by collide?

autumn lantern
#

so if i'm using a 2d array and to pathfinding jobs use the same node inside that array, they will end up overriding each others parent

#

this is my node class

hard viper
#

are you doing BFS etc?

#

also you should just combine x and y into a Vector2Int

autumn lantern
#

i'm using a*

ashen yoke
#

not sure what you mean, you create structures to compute the path, minheap, queues etc that will be cleared once the path is done, you dont need to modify the actual grid

autumn lantern
#

ah so just store a list/struct instead of using the parent of the node

hard viper
#

there are several ways to do it

#

you can store a giant 2D array to get fast access of matrix to node

heady iris
#

The different A* operations will be fighting over that data.

#

I use Djikstra's in one place and A* in another. In both, I create a dictionary to map each node to its parent.

#

they aren't jobified, but..maybe I should try that (:

autumn lantern
#

Djikstra's looks awesome too, i like the way rimworld do it with regions

#

probably going to implement something similar

heady iris
#

I use Djikstra's for a search problem where I have no way to come up with a heuristic

#

i'm pathfinding over a graph with completely arbitrary connectivity and with no hints about how close I am to the goal

#

I use A* for goal-oriented action planning

#

in that case, I can estimate how close I am to the goal based on how many things still need to be accomplished

autumn lantern
#

ah that makes senses. I'm only looking at simple movement at the moment

heady iris
#

Movement is great for A* because you have a good heuristic

#

(the distance to the goal)

autumn lantern
#

yeah it's pretty good but with grids, it was having issues. i'm going to end up splitting the map up into regions and using Djikstra for bigger distances

heady iris
#

hierarchical pathfinding can be way more efficient

autumn lantern
#

will also help with use case where a pathfinding goal is innacessible like you mentioned

autumn lantern
heady iris
#

that's what you're doing :p

#

split the world into regions

#

pathfind from region to region, then within a region

autumn lantern
#

ooh lol. I've not implemented it yet, just thought it looked great

errant bolt
#

I'm trying to add the ability to link images/textures to a graph element in a custom node editor, does anyone know any good reference code/tutorials for that?

I've dug through the documentation and found input node features for stuff like how Shader Graph handles 2D Texture inputs, but that relies on a centralized property list, and I want to make something that links more individually on a node to node basis.

dapper fern
#

I've stumbled into a problem with TextMeshPro where if I pass a regular color into the font atlas material - it gets effed because it is an HDR color while I am working with regular colors in my project. I want to change the font color globally, hence why I am altering the material directly, however either because it is HDR, or because TMP Vertex Color property SOMEHOW affects it - the resulting color is always wrong, paler and brighter.

I understand that if I alter both Vertex Color and Face Color - it will show me the correct color, but I don't want to alter Vertex Color of every goddamn TMP field in my project, it's stupid!

For now I've removed [HDR] from all the colors directly in the shader. Colors still show up wrong in the editor, but in the game view they are fine. I don't know why this problem exists, or if this is a problem at all, but I hate this solution and everything about this issue. If anyone faced such issues with TMP and solved them - I'd like to know how.

heady iris
#

There's nothing special about it being an "HDR color"

#

all that does is allow you to pick colors with R/G/B values greater than 1

#

A color that you've cranked up past 100% intensity can start to look washed out, depending on the render pipeline and tonemapping settings

#

a super bright color in the HDRP will turn white with the ACES tonemapping setting, for example

thorn stirrup
#

With OnCollisionEnter2D( Collision2D otherObjectsCollision), i can get the contact point and normal of the other object colliding with the game object with the OnCollision method.
But how can I get the game objects contact point and normal with that other object?

runic nimbus
#

Hey guys!

#

Two handed grab with an offset

#

Just think of how you would grab a gun like that, one hand on the grip, and one hand off to the side where the foregrip is

#

I've been stuck on this for days and would really appreciate if a quaternion wizard came in to help.

#

Thanks!

high summit
#

I am currently trying and failing to make a general purpose interaction system. I'm able to get it sort of working, but the players hitbox gets in the way of the raycast when you start looking downwards. This is my current code: ```cs
void Update() {
RaycastHit hit;

    int playerLayer = transform.root.gameObject.layer;

    int layerMask = ~(1 << playerLayer);

    bool hitInteractable = Physics.Raycast(interactionSource.position, interactionSource.forward, out hit, interactionRange, layerMask);

    if (hitInteractable)
    {
        IInteractable interactable = hit.collider.GetComponent<IInteractable>();
        if (interactable != null)
        {
            interactionPromptUI.SetActive(true);
            if (Input.GetKeyDown(KeyCode.E))
            {
                interactable.Interact();
            }
        }
        else
        {
            interactionPromptUI.SetActive(false);
        }
    }
    else
    {
        interactionPromptUI.SetActive(false);
    }
}``` This script is attached to the playerCamera, which is a child of the playerCapsule
#

Also not happy with how messy the code currently feels

#

Instantly realized I didn't actually set the players layer to anything different so I feel a bit dumb, though I'd like this system to work in multiplayer down the road anyways so this solution isn't future proof, as currently youd be able to interact with stuff through another player

lean sail
# high summit Instantly realized I didn't actually set the players layer to anything different...

is this first person or 3rd person? i assume 3rd. Maybe regardless you could find a way to start the raycast inside the player so it does not detect the player. Could play around with where the interactionSource is depending on how the player is looking.
Otherwise you could start a 2nd raycast if the first one hit your own collider. There is also stuff like RaycastNonAlloc but you would need a 2nd raycast anyways or some comparison to see which object is closest

high summit
#

The raycast starts from the camera which is inside the player

#

Actually now that you said that I checked and the camera was only partially in the player

lean sail
#

it shouldnt be hitting the player then at all

high summit
#

I think that was the issue

#

Just tested and that was it thank you

#

πŸ€¦β€β™‚οΈ

swift falcon
# runic nimbus I've been stuck on this for days and would really appreciate if a quaternion wiz...

FromTo guarantees that From will go to To, but doesn't give you very much control over the complete orientation. Imagine you hold your hands as if they were aiming a sniper at a target. You know if there were a sniper in your hands it would be pointed at the target. But that sniper could be upside down with your pinkie on the trigger or on its side, and in fact could be rotated any angle about that axis. Therefore making From point at something is not enough.

Not 100% sure but suspect this could be leading to the behaviour in ur test.

Will think harder on a solution.

high crow
#

hello there i am trying to make a grounded check in unity 2d after a few months of not using unity but for some reason it changes to grounded then stays like true.

#

this is my code grounded = Physics2D.Raycast(transform.position,Vector2.down,Distance,LayerMask.NameToLayer("ground"));

spring creek
#

And where do you check the grounded state?

high crow
#

1 i have used draw ray to check it

#

update

spring creek
#

Ok hmm. Good for both

swift falcon
high crow
#

yes

spring creek
#

And only the ground has the ground layer?

high crow
#

yes everything else is defult

spring creek
#

Oh daaang

high crow
#

ahhh

spring creek
#

I never use NameToLayer so I always forget

high crow
#

so do i have to difine a layer mask i have never done that before

swift falcon
#

layermasks got me for like a week before i figured it out

quartz folio
#

I provide all the solutions on that page

high crow
#

ok ill test it out thanks for the help

#

ok so i initialized the layermask with... public LayerMask layermask then changed my code to be grounded = Physics2D.Raycast(transform.position,Vector2.down,Distance,layerMask); now grounded doesn't change from false btw i did remember to change it in the inspector

errant bolt
#

Does anyone know how to have textures/sprites linked within nodes in a custom graph view?
I've got foldouts/input + output ports for linking but I can't seem to find anything in the documentation that refers to other 'bindable elements'

#

I have the data structure to store the image/anchor positions I need for the system I'm working on but I'm not sure how to make the graph view draw an image/texture field into a node.

frail cove
#

create a visual element and set its background to the sprite/texture?

#

or use a preview container

sleek bough
#

@full oar Don't cross-post

full oar
#

womp womp

dapper fern
heady iris
#

I don't like the transform.rotation *= line. That's probably what's causing the wild spinning

heady iris
#

it's just a scaling factor for the R/G/B values it's showing you

#

I forget the base, but if the color picker is showing red = 0.5 and an intensity of 10, then the actual red value is 0.5 * base^10

mild holly
#

Hey guys, I am trying to make a 3d platformer game and I got the player controls by the standard third person controller assets, I want to make a rotating asset I have shown such that it makes the player slip, right now as the player is based on character controller, it does not have simulated physics that allow that

swift falcon
#

for my physics based grab system what forcemode do i want to have when trying to get it to a target position?

heady iris
#

probably a continuous force

#

and one that depends on the mass of the object

#

so, the defualt force mode : ForceMode.Force

leaden ice
#

It depends on how "snappy" you want this to be

lunar python
#

if you want to grab something and have it interact with other physics body then sure check this out:
https://discussions.unity.com/t/difference-between-forcemode-force-acceleration-impulse-velocitychange/103470/4

swift falcon
#

alright

lunar python
#

Anyways I need serious help, my code is becoming spaghetti. I want to ask about how to clean up Coroutines when they are suddenly interupted during a phase. Currently the WallCling would interupt the jump and I would need to reset the variables depending on the phase of coroutine. I have considered making functions for each phase but that would quadruple the codes' length.
Here's my code: https://paste.ofcode.org/77TsxASkNnH4rRNMxUcaPx

#

Btw, you could also give me some recommendations to organize code better

lunar python
#

the host is broken currently

#

idk why

#

ok host is up again

heady iris
#

I want to set all of the knots in a Spline. It looks like calling SetKnot winds up doing a lot of extra work per call -- it's dirtying the spline and doing some other work every time I call it

#

There's a SetKnotNoNotify method that skips this. I'm planning to just do this:

#
for (int i = 0; i < knots; ++i) {
  // calculate some stuff
  if (i < knots - 1)
    spline.SetKnotNoNotify(...);
  else
    spline.SetKnot(...);
}
#

I don't know if this is going to cause some weird internal problems for the spline

#

I'm just going to tryitandsee but I'm curious if I'm missing something here

static matrix
#

is a virtual function like an abstract function but you don't have to override it?

hard viper
#

virtual function has an implementation already, that you can choose to use or not use

static matrix
#

ah ok
cool

hard viper
#

you can also do
public override void DoX() {
base.DoX();
//My own DoX
}

static matrix
#

nice

final junco
#

Hi, I'm trying to use a simple grab and drop object script and I'm having a problem with it. If I look down with the object on my hand the object will collide with the player and send him backwards.
How could I disable the collider only between the player and the object when it is in the player's hand?

heady iris
#

You can make specific colliders ignore collisions.

final junco
#

oh that is perfect thank you

hard viper
heady iris
#

although, this generates garbage...

#

the problem is that I can't call SetDirty -- it's an internal method

heady iris
#

i guess it's time to Embed That Package (tm)

heady iris
# heady iris

wow, this is a lot faster -- like, unreasonably faster

#

i have to triple-check this; i must be messing up the benchmark

#

oh, I had deep profile on, which was probably unfairly penalizing the one-by-one approach

#

This is still an enormous difference. This can't be right...

#

I created 16 4-knot splines and have a script that either:

  • calls SetKnot once per knot
  • makes a list and assigns it to Knots

SetKnot is taking about 3ms. Assigning to Knots is taking 0.15ms (and creates a lot of garbage, since it's making entirely new lists in there)

Both versions are working just fine..

heady iris
#

Looks like SplineCacheUtility -- an editor-only class -- is responsible; it tries to update some cached data instead of just throwing it all out

#

So it's not a runtime problem, but it sure is an editor problem...

earnest nebula
#

hello I keep having really weird problem
so I import strings from file and then write them out
they are loaded okay
but when writing them out they behave weirdly
well only the first letter
first letters behave like this:

sentence1[sentence1]
sentence2[sentence1]
sentence3[sentence2]

and so on
but the rest of the sentence and words are alright

i found one solution to this
copy the object, remove the original and it works
but just once
on other runs (and even builds it breaks again)

I am sending video and code snippet below

#

the weird thing is that it only breaks on some objects
even if they are from the same prefab

heady iris
#

oops, that was backwards

#

where do you reset textArea.text?

#

share the entire script

earnest nebula
#

i will share all related scripts
there are like 3 at work

heady iris
#

!code

tawny elkBOT
heady iris
#

use a paste site for them

earnest nebula
#

thank you

#

the last two are just the behavior of the write outs

#

WriteOutSentences load text from file

#

and WriteTextProlog prints sentences into text area

weak venture
#

It's rare but I sometimes fall through the one-way platform effector. Are there parameters I can mess with (like maybe the collider size?) that could make this more consistent?

swift falcon
#

how do i get the magnitude of a vector3

swift falcon
#

k im trying to add it to another vector3

knotty sun
#

can't add a float to a Vector3

weak venture
#

could add "new Vector3(float, float, float)" if you want

#

or only to whatever component you care about like "var xOffset = new Vector3(otherVec.magnitude, 0.0f, 0.0f);"

knotty sun
#

or v3 = v3 + (v3.normalized * otherVec.magnitude)

heady iris
errant bolt
#

I need an image anchor to embed a dropdown for an enumeration that tracks anchor position, and link/reference to an image in the project.

heady iris
# heady iris So it's not a runtime problem, but it sure is an editor problem...

I wound up embedding the Splines package and:

  • adding a SetKnots method that reuses the old BezierKnots and MetaData lists
  • getting rid of a ton of garbage allocation by not using IEnumerable in one place (manually iterating over four lists instead of using a method that iterates over them for you) and by avoiding a Select in another place (which was also super simple)

0 GC allocated per SetKnots call! It runs way better in the editor, and it also runs better than calling SetKnot repeatedly in the build.

Most importantly, it still appears to work correctly, too πŸ˜‰

tranquil canopy
#

Hello everyone! I'm currently working on developing a visual asset for Unity aimed at managing JSONs in a more intuitive manner. But i've found a little problem...

I'm seeking an efficient method to handle custom data types within my asset. Specifically, I want to enable users to seamlessly add their own data types. For instance, consider a scenario where a user wishes to introduce a data type named 'WeaponType' with various values such as 'Rifle', 'Pistol', 'Shotgun', and so forth.

My aim is to ensure that my asset remains flexible enough for users to define and utilize their custom data types visually. However, the complexity lies in these data being of a custom type, not simply float, char, int, or string.

Given this context, any ideas?

latent latch
#

parsing

heady iris
#

you're describing a super broad problem

weary swift
#

!code

tawny elkBOT
weary swift
#

Yo ! I have a function that allow me to activate and deactivate the weapon hitBox at a certain % of the animation. If I press attack while attacking, my player will change the attack animation. I want first animation to crossfade to the next one. The problem is, if I use crossfade the animation normalizedTime isn't really the one of the next animationAttack, but a mix of the previous and the next. This prevent me from actually knowing if i'm at 50% of the animation for example. What should I do to be able to crossfade while still having my function hitBox working ? PS : If I use Play instead of CrossFade it works perfectly fine, in case your'e wondering
https://gdl.space/emawiboqey.cs

hollow halo
#

Hello, I have a question, about my Unity WebGL Build project. Where I'm making a C# Script call javascript functions. Before i ask, i guess my main problem would be I don't have a deep understanding of Javascript or C#, but I'm trying. I made a Javascript plugin, put it in my asset folder, and created a C# Script that calls a function from the .jslib file. This script runs fine on the browser after i build the project, however, im kind of puzzled as to why I get this error ```EntryPointNotFoundException: GetUserAgent assembly:<unknown assembly> type:<unknown type> member:(null)
DeviceInfo.Start () (at Assets/Script/DeviceInfo.cs:20)

#

When I test my build, this function gives me an issue

tranquil canopy
swift falcon
#

Does anyone know if this dialogue system supports event based dialogue, like you can make a script or something do something after a dialogue choice has been selected: https://github.com/merpheus-dev/NodeBasedDialogueSystem

Or does anyone know of some branching dialogue system like that

GitHub

Node Based Dialogue System for Unity. Contribute to merpheus-dev/NodeBasedDialogueSystem development by creating an account on GitHub.

weary swift
final junco
#

Hi I am working on a pick up and drop object script and I wanted to make it so if I fling the camera before dropping it, it throws the object with the force applied to it but I'm having some problems trying to do that.
I tried it this way:
Vector3 desiredPosition = holdArea.position + holdArea.TransformDirection(objectOffset);
Vector3 moveDirection = (desiredPosition - heldObj.transform.position);
heldObjRB.velocity = moveDirection * pickupForce * Time.fixedDeltaTime;

and objectOffset is defined like this:
objectOffset = holdArea.InverseTransformDirection(pickObj.transform.position - holdArea.position);

and it wasn't the best solution because it just keeps getting close to my face if I run, what could I do to make it stay more in place on the holdArea?

swift falcon
twin lintel
#

does anyone know how can i populate an objects array automatically, like without having to drag and drop my objects in the inspector multiple times? i wanna automate it because im working with too many objects and i have to repeat the process for different scenes with different objects..

rigid island
#

also why not use prefabs, anything you do in one scene should affect all other prefabs

twin lintel
#

oh yea sorry i meant prefabs list

rigid island
#

like a list of prefabs ?

twin lintel
#

yea

#

i can fill it by drag and dropping my objects but it takes so much time

rigid island
#

if its a common shared list, put them in a scriptable object, you can have all other objects refer that list

twin lintel
#

mhm ill see thanks

terse aurora
rigid island
#

or your Movement script

#

make the rigidbody dynamic and use velocity / addforce to move instead

weak venture
#

does collision still work normally on kinematic?

rigid island
#

afaik you have to do your own collision checks

weak venture
#

maybe try dynamic with gravity scale 0 if you want physics

rigid island
#

it pushes other bodies but will phase thru walls

terse aurora
weak venture
#

you can set gravity scale on a dynamic rigid body i think

rigid island
#

you can only set velocity on your X in your movement

terse aurora
rigid island
#

you don't want gravity ?

terse aurora
rigid island
#

oh ok

terse aurora
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    private Rigidbody2D rb;
    private BoxCollider2D coll;
    private SpriteRenderer sprite;
    private Animator anim;
                                   //  w       s     a      d
    private bool [] inputsHolder = { false, false, false, false}; 
    [SerializeField] private float moveSpeed = 2f;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        coll = GetComponent<BoxCollider2D>();
        sprite = GetComponent<SpriteRenderer>();
        anim = GetComponent<Animator>();

    }

    // Update is called once per frame
    private void Update()
    {
        rb.velocity = Vector2.zero;
        if (Input.GetKey("w")) inputsHolder[0] = true;
        if (Input.GetKey("s")) inputsHolder[1] = true;
        if (Input.GetKey("a")) inputsHolder[2] = true;
        if (Input.GetKey("d")) inputsHolder[3] = true;

        if (inputsHolder[0] == true) rb.velocity = new Vector2(0f, moveSpeed);
        if (inputsHolder[1] == true) rb.velocity = new Vector2(0f, rb.velocity.x - moveSpeed);
        if (inputsHolder[2] == true) rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
        if (inputsHolder[3] == true) rb.velocity = new Vector2(rb.velocity.x + moveSpeed, rb.velocity.y);

        UpdateAnimation();
        FillWithFalse(inputsHolder);
    }
}

Does it seem like a good code for movement or you can find some good changes for it?

rigid island
#

yes..

terse aurora
#

because I don't feel like writing always new Vector2 is a good thing, but I'm not sure you can change it because I'm new to c#

rigid island
#

many changes needed

lean sail
#

im sure there are tutorials online that have better code

rigid island
#

for wasd I would just do

Vector2 input;

input.x = Input.GetAxis("Horizontal")
input.y = Input.GetAxis("Vertical")

weak venture
#

You dont need input holder here, you might as well just set on the previous check. Also if its gonna be top down like pokemon maybe its just easier to use translation based movement? Can be more finite/discrete that way

weary swift
terse aurora
terse aurora
rigid island
weary swift
#

Oh ok, np thanks !

#

I will ask again tomorrow

compact carbon
#

hey quick question how can i put a lerp in a function and then call that function whenever to do the lerp?

rigid island
#

well yea.

#

where else would you put a lerp

lean sail
compact carbon
#

well no not exactly im a bit confused because when i put it in a function it only does it once but when its in update it works fine?

#

does it need to be in a IEnumator?

#

this is the code

#

when i put this lerp thats in update into the UpLerp Fucntion it dosent work

weary swift
rigid island
#

check this out

compact carbon
#

ohhhhh

compact carbon
hollow halo
#

I am getting spanked by this next step. is anyone familiar with Emscripten? Ive go through 10-12 hours of reading regarding my issue, and this error seems to be abit trivial to diagnose 😦

compact carbon
#

ok i have a new problem, i have called one lerp but i want to then call another in a different function and it seems to not wait till the Coroutine is done to do the next one any ideas?

latent latch
#

what exact behaviour are you going for

#

oh, you may need to yield till the next frame if you're just falling out the the scope

#

oh, but the resource up there basically tells you how to exactly write for it with lerp

terse aurora
#

not blurry, I meant glitchy

delicate flax
versed spade
#

For this section option. Is the Scriptable Object class the Visual Scripting Scene variables, a component (like Variables Component), or a normal C# class but instead of MonoBehavior it is Scriptable Object?

#

Sorry for the age old reply. got distracted with work through the past days

heady iris
terse aurora
heady iris
#

ScriptableObject is kind of a unity object. You can serialize instances if them as assets and reference them front elsewhere

#

I’m not very familiar with Visual Scripting, so I can’t say if it’s similar to something from that system

versed spade
#

I personally wasn't finding an object called ScriptableObject in the menu, which was why I was confused.

Also my intention is for this ShipData database, is for the game to spawn it in depending on the user selected ship, so the data will change depending on what the player selected. PlayerLoadout handles what to spawn. ShipData is stuff like maxVelocity, turnRate, etc on the specific ship.

Since this is an object I assume it should work fine

weary swift
heady iris
#

It's much like how you derive from MonoBehaviour to create your own kinds of components.

delicate flax
# terse aurora and how to fix it

that I can't really help with as I'm not an expert on the issue, I just know enough to recognize it πŸ˜…
my impression is that there are many ways to solve it, but it depends quite a bit on the game, engine and setup. hopefully someone else here knows more, if googling pixel perfect camera does not yield any results.

I know unity has this component, but I honestly have no idea if it's related to your problem, sorry.
https://docs.unity3d.com/Packages/com.unity.2d.pixel-perfect@1.0/manual/index.html

heady iris
#

Animation events might be a more reliable way to do this.

versed spade
weary swift
heady iris
#

You might need to filter the events based on the weight of the animation state. Otherwise, the fading-out attack might fire whilst it's almost completely faded out.

#

including animationState and animatorStateINfo

weary swift
#

Ok thanks, I guess it's the right way to go

compact carbon
#

how do i detect if my mouse pointer is hovering over a CERTAIN ui element?

terse aurora
heady iris
#

OnPointerEnter will get called on it.

#

You can also use EventTrigger component to do this entirely in the inspector

#

it lets you add callbacks for each kind of event

compact carbon
#

ok let me break down what im tryna do

#

im trying to make it so when you hover over a Level select it changes to show that level on the main worldspace, i ve got everything except the ui hover detection

heady iris
#

Put it on whatever the graphic is attached to

latent latch
#

there's a few input calls you can do depending if you're using the new input system or not

#

actually I dont think that matters anymore? Maybe they both work

#

there's one other call I know because I know I ran into issues with this using it with the callbackcontext of the new (not really new anymore) input system

#
public class CanvasRaycaster : MonoBehaviour
{
    GraphicRaycaster m_Raycaster;
    PointerEventData m_PointerEventData;
    EventSystem m_EventSystem;

    void Start()
    {
        m_Raycaster = GetComponent<GraphicRaycaster>();
        m_EventSystem = GetComponent<EventSystem>();
    }

    public bool IsPointerOverCanvas()
    {

        m_PointerEventData = new PointerEventData(m_EventSystem);
        m_PointerEventData.position = Input.mousePosition;

        List<RaycastResult> results = new List<RaycastResult>();

        m_Raycaster.Raycast(m_PointerEventData, results);

        if (results.Count > 0)
        {
            return true;
        }

        return false;
    }
}```
Ah, there's this way too I probably grabbed from the forums, but it's just a cleaner way to do this than above.
sterile sorrel
#

Im trying to instantiate a ramp object, it works, but I need it to instantiate in the length of a float called chunkLength, any ideas?

'public float chunkLength = 90;'

' GameObject[] rampEMPTY = GameObject.FindGameObjectsWithTag("rampTag");

foreach (GameObject position in rampEMPTY)
{
Instantiate(ramp, position.transform);
} '

delicate flax
#

#πŸ’»β”ƒcode-beginner message
same question, new variable names?
is the problem that it's not spawning at the correct location, or do you want to change the scale of the object you spawned to 'cover' chunkLength?

cosmic rain
sterile sorrel
# cosmic rain Wdym by "in the range of the float"?

im instintiating ramp objects into empty game objects with the tag rampTag, it works, the chunks with these empty objects have this script that Instantiates these ramps, but since multiple spawn, they duplicate into past chunks

i need it to only generate in a certain range to prevent this

spring creek
#

Still don't really understand though

sterile sorrel
#

that doesnt work

#

full thing

GameObject[] rampEMPTY = GameObject.FindGameObjectsWithTag("rampTag");

foreach (GameObject position in rampEMPTY)
{
if (Vector3.Distance(position, ramp) < chunkLength)
{
Instantiate(ramp, position.transform);
}
}

spring creek
#

You are using position in the distance check

#

And position.transform in the instantiate?

#

What is position

delicate flax
#
GameObject[] rampEMPTY = GameObject.FindGameObjectsWithTag("rampTag");

foreach (GameObject position in rampEMPTY)
{
    if (Vector3.Distance(position, ramp) < chunkLength)
    {
        Instantiate(ramp, position.transform);
    }
}```

looks like `ramp` is your prefab? so you can't really `Vector3.Distance` on that
sterile sorrel
cosmic rain
#

Share the errors then.πŸ€·β€β™‚οΈ

spring creek
spring creek
sterile sorrel
#

Argument 1: cannot convert from 'UnityEngine.GameObject' to 'UnityEngine.Vector3'
Argument 2: cannot convert from 'UnityEngine.GameObject' to 'UnityEngine.Vector3'

#

!code

tawny elkBOT
spring creek
#

You use a position

#

Well, two positions of course

sterile sorrel
#

This is what ive got

#

I should have posted it like this first anyways

#

no one can understand little code bits without context

spring creek
#

If you use a link, why not post the whole file?

sterile sorrel
#

i did it