#archived-code-general

1 messages · Page 329 of 1

heady iris
#

right, since you'd get two variants that are unconditionally taking one side of the if / else branch

#

but a branch on a uniform doesn't diverge: every single thread is going to take the same path

rotund girder
#

hey can someone help

#

im a new scripter and snippets arent showing up for me on vs

heady iris
#

do you mean you're getting no autocomplete or error highlighting at all?

leaden solstice
heady iris
#

because the branch is based entirely on a uniform

spring creek
rotund girder
rotund girder
leaden solstice
heady iris
#

the problem is that this causes Shader Variant Hell very quickly

leaden solstice
#

True, it's multiplying every time you add something like that sure

serene stag
spring creek
leaden solstice
heady iris
#

i mean, skipping a calculation if I'm not using a feature is pretty standard

leaden solstice
#

Usually involves using other resources tho. I do like to see benchmark on that

vagrant knot
#

I'm trying to create a gravity switcher mechanic and I'm failing to use quaternions/rotations to reorient and remap player input to handle movement.
Would someone hop in 5min call so I can show current state and ask questions?

spring creek
heady iris
#

Show your code and we can probably help.

rotund girder
#

I jus downloaded visual studio

#

the download keeps failing though

#

😭

rigid island
#

also !install

tawny elkBOT
#
When Unity fails to install checklist
  • Make sure you have enough space including on C: drive.
  • Check that it's not being blocked by antivirus/security programs.
  • Look through the logs for a real reason why the setup fails they are pinned [here](#💻┃unity-talk message).

If you still have issues, perform a clean install in another location:

  • Install the Hub and Unity in a non-system drive or a clean new folder in the root of C: drive.
  • Failing that use the recovery Refresh option or reinstall OS entirely then repeat the previous step.
rotund girder
leaden solstice
heady iris
#

I guess that a uniform is basically equivalent to a dynamic_branch at that point

leaden solstice
#

But it is equivalent

#

Or use custom function and code it.. lol

slim gate
#
public static Dictionary<Id, Sprite> LoadTexturesFolder()
{
    Dictionary<Id, Sprite> sprites = new Dictionary<Id, Sprite>();

    string folderPath = Path.Combine(Application.persistentDataPath, Data.TexturePath);

    if (Directory.Exists(folderPath) == false) { return sprites; }

    string[] filePaths = Directory.GetFiles(folderPath, "*.png", SearchOption.AllDirectories);
    foreach (string filePath in filePaths)
    {
        Texture2D texture = LoadPNG(filePath);
        if (texture != null)
        {
            string fileName = Path.GetFileNameWithoutExtension(filePath);
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);

            sprites[new Id("scourgefall", fileName)] = sprite;
        }
    }

    return sprites;
}

private static Texture2D LoadPNG(string filePath)
{
    Texture2D texture = null;
    byte[] fileData;

    if (File.Exists(filePath))
    {
        fileData = File.ReadAllBytes(filePath);
        texture = new Texture2D(2, 2);
        texture.filterMode = FilterMode.Point;
        texture.LoadImage(fileData);
        texture.Apply();
    }
    else
    {
        Debug.LogError("File not found: " + filePath);
    }

    return texture;
}

So I have the above to load in some .png files at runtime. In the editor I can go into the Sprite Editor and edit: Custom Physics Shape and Secondary Textures. Is there a way to assign/ apply these somehow directly in the code at runtime too?

I want to:

  • apply a secondary texture to a loaded sprite with a specific name like "_Emission" etc.
  • Ideally also set a custom physics shape somehow per code

Any way to do this?

leaden ice
slim gate
# leaden ice Physics shape: https://docs.unity3d.com/ScriptReference/Sprite.OverridePhysicsSh...

Oh, thanks alot!
I think I realize what you mean; The material has 2 Textures exposed as properties in the shadergraph: For example. "_MainTex" and "_Emission". Then I can just apply these 2 properties with the 2 textures I want. The textures themselves arent related at all and I set them seperately in the material.
I had the wrong Idea of how it worked i think, Is the above correct?

#

It just confused be cause in the editor I would just set the "_Emission" as a secondary of the "_MainTex" and not assign it to the material too
I guess the engine does that step for me when its the secondary texture with the proper 'id'?

old linden
#

What is the obvious reason I can't reference my VectorCache class from a MonoBehaviour class? 😂
I have no Errors to resolve

knotty sun
#

you can reference Assembly-CSharp from Assembly-CSharp-Editor but not the other way round

somber nacelle
old linden
#

I have no idea why it's there 😂

somber nacelle
#

did you perhaps put it in a folder called Editor?

knotty sun
#

it's in an Editor folder ?

old linden
#

Ah. I am extending a downloadable tool and didn't realise when I dropped it in. It certainly is. Thanks a bunch

heady iris
#

yeah, if you don't add your own assembly definitions, Unity puts anything in an Editor folder into a separate Editor assembly

old linden
#

Is there a way to keep it in the Editor folder, but have it in the standard assembly?

somber nacelle
#

why does it need to be in the Editor folder?

old linden
#

It's only used for Editor tools

#

Ok no probs Il just move it

knotty sun
#

obviously not

old linden
knotty sun
# old linden What?

well if it was supposed to be editor only and you are referencing it in Assembly-CSharp then it is not Editor only or you have a serious design problem

old linden
knotty sun
leaden solstice
#

But now then your Editor folder is not for Editor

heady iris
#

You'll just have to make sure that you don't have any references to it when building the game

#

You can have the entire script inside an #if UNITY_EDITOR block

old linden
#

It's not worries I just moved it. The class that requires it stores editor data for Editor and Gameplay functionality and rewriting that would be a massive undertaking

dawn nebula
#

Finally, working splines. Just tried it on 2022.3.31f1

knotty sun
somber nacelle
#

the fix was pushed in 6000.0.4 and 2022.3.31 so it should work in either

vital oracle
#

For grid based games what is the common practice to store and manage data associated with the grid.

Say the level map is a 2D 100x100 grid. You would want to store the grid position of the player, enemies, items/interactables, obstacle and walkable grid positions, etc. And also be able to change the positions of these elements and access their associated data easily, i.e. enemies moving each turn or a randomly generated level so the walkable and obstacle positions need to be changed.

leaden ice
#

If the data is dense, it usually makes sense to use a 2D array, e.g. GridSlot[,]

#

If the data is sparse, I would use something like Dictionary<Vector2Int, GridSlot>

vital oracle
leaden ice
#

What I mean by dense and sparse is, will the grid be mostly empty? If it's mostly empty, the data is sparse.
If most or all of the spots will always have some data associated with them, it is dense

#

The nice thing about the Dictionary is we don't need to store any data for empty slots. This makes it more memory efficient than the array when dealing with a sparse grid

#

But the Dictionary comes with slightly higher costs for adding and retrieving elements, so if the grid is dense, we may as well just use the 2D array since we will need to hold all that data anyway.

fleet tide
vital oracle
# leaden ice What I mean by dense and sparse is, will the grid be mostly empty? If it's mostl...

Hmm, well I wasn't talking about a specific game I was making, more to start planning the data structure of one.

Lets say of the level grid there would be at least 30-40% of the grid positions that would be obstacles and structures, the rest would be sparse with maybe a few enemies that move around the map and some items to interact with.

I've done a game with grid movement, but just used a collision system for movement as I didn't really need any data storage. But I'd like to instead not use collisions and just use the underlying grid data to place characters and move them.

gray mural
leaden ice
leaden ice
fleet tide
gray mural
tawny elkBOT
leaden ice
# fleet tide Oh yeah sorry ahah
    private void UpdateIndicatorPosition(Transform enemyTransform)
    {
        Vector3 screenPos = mainCamera.WorldToScreenPoint(enemyTransform.position);
        indicatorImage.transform.position = screenPos;
    }```
You should check here if `screenPos.z < 0` and if it is, hide the image
vital oracle
fleet tide
gray mural
# fleet tide Simply ?

You don't have 2 circles, it's just that the circle is drawn even when the enemy is not visible to the player.
The z position returned by the WorldToScreenPoint method is the world units from the camera, so if the enemy is not visible to the player, which rotates the camera, then its z position is smaller than the one of the camera.

fleet tide
gray mural
#

The enemy should just be detected when the camera sees it. This means its z position is greater and in camera's range

plucky holly
#

What is wrong with unity's rotations? I have a cube and I have a decal that's is rotation depending on the rotation of the cube no matter which face is facing up so when I put it down, the decal is align with the cube. but when the y axis is facing down, it acts weird.

plucky holly
#

I use a very simple script for it

plucky holly
#

the other why I tried was this

        _angle = vector3.angle(vector3.up, transform.right);
        _rotation = transform.localeulerangles;
        upf = mathf.abs(vector3.dot(vector3.up, transform.up));
        rightf = mathf.abs(vector3.dot(vector3.up, transform.right));
        forwardf = mathf.abs(vector3.dot(vector3.up, transform.forward));

        up = upf > rightf && upf > forwardf;
        right = rightf > forwardf && rightf > upf;
        forward = forwardf > upf && forwardf > rightf;

        if (up)
        {
            _angle = transform.localeulerangles.y;
            vector3 _rot = transform.localeulerangles;
            _rot.x = 0;
            _rot.z = 0;
            decaltransform.eulerangles = _rot;


        }
        else if (right)
        {
            quaternion targetrotation = transform.rotation;
            targetrotation.y = transform.rotation.y;
            targetrotation.x = 0;
            targetrotation.z = 0;
            decaltransform.rotation = targetrotation;
        }
        else if (forward)
        {
            quaternion targetrotation = transform.rotation;
            targetrotation.y = transform.rotation.y;
            targetrotation.x = 0;
            targetrotation.z = 0;
            decaltransform.rotation = targetrotation;
        }
#

and this time the problem was only this Z

knotty sun
#

still trying to modify quaternion properties. DONT

plucky holly
somber nacelle
knotty sun
#

When you do Quaternion->Euler A->Quaternion->Euler B. A and B will almost certainly not be the same

leaden ice
#

YOu might also have a "terrain layer" which is probably pretty dense and an "items layer" which maybe has enemies, chests, items, etc which would be sparse.

plucky holly
somber nacelle
#

show what you tried

plucky holly
#

it still doesn't make sense that it only acts weird in one axis

heady iris
#

the behavior is not intuitive

plucky holly
#
Vector3 _rot = transform.localEulerAngles;
_rot.x = 0;
_rot.z = 0;
decalTransform.eulerAngles = _rot;

this is what I first tried

#

this one acts weird on Z axis up or down

plucky holly
vital oracle
leaden ice
#

I would recommend rather than GameObject though, to have a component like GridElement which goes on all of the different things

leaden solstice
#

I assume you want your decal to follow the axis that is most upward

#

Other option would be just locking Y axis

earnest pawn
#

I'm making a tower defense and I have a tower I would like to do something whenever each round ends (give the player bonus money). I have a level manager game object that handles spawning enemies/updating rounds and such, and I could just have the tower look for a change in the round variable each frame but that sounds like an awful design choice. I don't want the level manager to have to have an array of all of this type of tower or anything like that, so is there a way I can set up a callback across objects? Essentially have my tower look at the level manager and whenever it updates the current round, it runs it's function.

leaden ice
#

have the tower listen to the event

old linden
# plucky holly so what should I do?

To mimic a single axis and maintain whatever values are on the other axis try:
transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, otherTransform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)

#

Or to nullify the outlying axis', replace them with 0

earnest pawn
barren rapids
#

OverlapCollider not finding colliders

fleet tide
#

Hey ! Someone know if it's difficult or not to create a launcher for my game ? I want create it for upload new version of my game to my friend without download it again ^^

plucky holly
#

first I tried to check which axis is on top and get the rotatins depending on that

#

but that didn't work as expected

plucky holly
lean sail
fleet tide
lean sail
fleet tide
pulsar holly
rigid island
#

also don't crosspost

pulsar holly
#

I instantiated

rigid island
#

where?

pulsar holly
rigid island
#

typically can tell what goes on, but here I'm genuinely confused what is even going on. Very messy

#

is this some tetris type of game?

naive swallow
#

Yeah, no I'm out I'm not trying to make sense of this

#

this is an absolutely unmaintainable mess and will be basically impossible for anyone else to make sense of it

#

Not to mention the fact that you are repeating everything over and over again

rigid island
#

was about to say, lots of redundant code

naive swallow
#

to the point that you are literally setting all of these booleans to false twice in a row inside of your horrifically repeated code blocks

#

I say this with absolutely no hints of irony, and as a 100% serious suggestion: All three of these scripts should be deleted and remade from scratch

#

Do not reference any old code, make them out of whole cloth. This is a slapdash mess of bandaids and no longer resembles programming in its current state

somber nacelle
weary swift
#

Yo ! Do you know any famous/good written 3D games created in Unity that have the code open source ?

#

Lmao I'm asking here because I searched google and I didn't find anything meaningfull

weary swift
#

I'm asking for recommendations here not for a list... Therefor humans are better at this than google...

rigid island
#

the human thing to do is doing your own research like all of us do

weary swift
#

Yeah ok

#

If you think so

weary swift
#

OMG ! For example I didn't know about this, you could just answer with this but putting a google reaction seams better...

#

Thanks

lean sail
#

Unless you're trying to just rip code, I doubt you'll really find what you want in open source code.

rigid island
#

um yeah if you're lazy thats on you

somber nacelle
#

"guys where can i find open source projects"

doesn't know about searching on github

rigid island
#

fr

weary swift
somber nacelle
#

yeah, i mean who wouldn't do literally the bare minimum to research open source software

weary swift
lean sail
#

Unless you dedicate a decent amount of time to actually learning the codebase

weary swift
#

Ok

full canopy
#
transform.localRotation = Quaternion.identity;
transform.localRotation *= Quaternion.FromToRotation(-attachTransform.forward, transform.forward);```
the code above has different results depending on if attachTransform is a child or grandchild of transform. Why?
attachTransform's world rotation does not change, only whether it is a direct child or a grandchild.
#

unless I'm wrong, transform.forward returns a world-space vector no?

leaden ice
#

Yes transform.forward is world space

full canopy
#

grab point (attach transform) in grandchild v.s. direct child

leaden ice
full canopy
#

yes

leaden ice
#

And what are the two different results you see?

full canopy
#

child v.s. grandchild (held at same angle)

#

one's basically backwards for some reason

#

hold on

#

i uh

#

may be incredibly stupid

#

yeahhhh

#

sorry @leaden ice

#
{
    transform.parent = selectingObject.transform;
    transform.localRotation = Quaternion.identity;
    transform.localRotation *= Quaternion.FromToRotation(-attachTransform.forward, transform.forward);

    //transform.localRotation *= Quaternion.Inverse(attachTransform.localRotation);

    transform.position = selectingObject.transform.position + (transform.position - attachTransform.position);

    if (useRigidbody)
    {
        attachedRigidbody.isKinematic = true;
    }
}
else if (activating)
{
    transform.parent = activatingObject.transform;
    transform.localRotation = Quaternion.identity;
    transform.localRotation *= Quaternion.Inverse(attachTransform.localRotation);

    transform.position = activatingObject.transform.position + (transform.position - attachTransform.position);

    if (useRigidbody)
    {
        attachedRigidbody.isKinematic = true;
    }
}
else
{
    Drop();
}```
what i wrote was in the if (selecting) portion
#

but the interaction is in the if (activating) portion so it just never actually changed anything

#

on a second note though, what is the best way to get the local rotation between 2 objects if one is not a direct child?
Quaternion.FromToRotation(-attachTransform.forward, transform.forward) did not work as i thought it would and is not consistent either

#

transform.localRotation *= Quaternion.Inverse(Quaternion.Inverse(transform.rotation) * attachTransform.rotation);
turns out this is the actual answer. Ive tried so many things involving quaternion.inverse and never thought about using it twice like that

serene stag
weak venture
#

I have vsync disabled in quallity settings. Also trying to override in code just in case
Application.targetFrameRate = -1;
QualitySettings.vSyncCount = 0;
But I'm still seeing it drop down to a lower frame rate and wait for vsync in the profiler. Is there some other place I need to disable vsync?

dire marlin
#

my game has a save system and on some of my beta tester's builds the new game button doesn't work and the load game button freezes the player's character in the wrong place

#

i'm not sure why this is happening

lean sail
# dire marlin i'm not sure why this is happening

sounds like you need to get to adding more logs and seeing whats happening for real. What you've described is what the beta tester probably said, as the dev you need to dig deeper. For a button not working, id first check to see if its covered by anything. Maybe they are on a different resolution, where things just shifted enough so that the button is covered by some invisible thing they are clicking instead.
For the other part you mentioned, this isnt enough information to suggest anything. Check for errors possibly, check to see if input is being registered. What is "freezing in the wrong place"?

lean sail
# dire marlin its the code

this couldnt be more vague. Surely theres something more you've reached in your conclusions like if the data gets logged and is correct

#

you are giving very little information to go off of

dire marlin
#

SaveManager script

#

keep in mind this only happens on some peoples computers

#

everyone else's worked fine

#

my friend's specifications

Processor Information:
CPU Vendor: AuthenticAMD
CPU Brand: AMD Ryzen 9 7945HX with Radeon Graphics
Operating System Version:
Windows 11 (64 bit)
Video Card:
Driver: AMD Radeon(TM) 610M
DirectX Driver Name: nvldumd.dll
Driver Version: 31.0.24033.1003
DirectX Driver Version: 32.0.15.5585
Driver Date: 5 8 2024
OpenGL Version: 4.6
Desktop Color Depth: 32 bits per pixel
Monitor Refresh Rate: 240 Hz
DirectX Card: NVIDIA GeForce RTX 4090 Laptop GPU
VendorID: 0x10de
DeviceID: 0x2757
Revision: 0xa1
Number of Monitors: 1
Number of Logical Video Cards: 1
No SLI or Crossfire Detected
Primary Display Resolution: 2560 x 1440
Desktop Resolution: 2560 x 1440
Primary Display Size: 15.00" x 8.43" (17.17" diag), 38.1cm x 21.4cm (43.6cm diag)
Primary Bus: PCI Express 8x
Primary VRAM: 512 MB
Supported MSAA Modes: 2x 4x 8x

RAM: 31962 Mb

lean sail
# dire marlin

first thing !code
2nd is you shouldnt be using binaryformatter https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatters.binary.binaryformatter?view=net-8.0
But really i dont know what you're showing me this code for. My first message to you just said plainly what you need to do. Add more logs, and see whats actually happening. See whats running, see if any of those log errors get printed.
Anyone here wont just look at their pc specs and say "the lack of 3 monitors causes the issue".

tawny elkBOT
dire marlin
lean sail
#

its entirely possible the code youve shown isnt even related to the problem. What debugging steps have you taken to even assume this code is the issue?

dire marlin
#

new game doesnt work though when clicking

lean sail
lean sail
dire marlin
#

I have done some debugging

#

The buttons are interacted with but no errors

#

ig ill switch to player prefabs

lean sail
# dire marlin The buttons are interacted with but no errors

you need to start debugging a lot more about what specifically isnt working. Narrow it down to an exact line of code that isnt running, or is running with the wrong value. Im not sure how to make this more clear, that the fact a button isnt working isnt gonna help you find the issue

#

youve basically only said "button isnt working" then showed completely random code, that i cant even be sure is related to the button.

dire marlin
#

when you press this button this function starts

lean sail
# dire marlin when you press this button this function starts

Ok so you are claiming that the function starts, but also 10 minutes ago "new game doesnt work though when clicking". Do you see why i am telling you to debug more? You are assuming what is happening in code. What specifically doesnt work? What line of code? Figure this out then itll be more clear at least what the issue is

dire marlin
lean sail
#

best case is you would be able to get access to their setup, and setup a development build where you can breakpoint exactly whats happening. Though if this isnt possible, you'll pretty much have to rely on log files and videos

swift falcon
#

Guys I am so so so sorry for off topic, but I could not find a better channel to ask this, so i will just ask it here, where can i find a channel to casually tlak or report a user? Staff font reply to DMs

sleek bough
swift falcon
sleek bough
#

If you don't intend you use the server for Unity questions and spam off-topic instead you might as well leave now.

#

Your next post better be a valid server interaction.

swift falcon
sleek bough
#

ok then

#

!ban save 798096065949728808 Ignoring warnings. Spam.

tawny elkBOT
#

dynoSuccess mlssp166 was banned.

pastel patio
#

Hi guys, I'm having trouble with InputAction.GetBindingDisplayString

#

The sample uses legacy text for their key displays

#

But on mine, with it being TextMeshPro text, it somehow bugs and fails to display correctly

sleek bough
#

Is debugging printing out correctly?

pastel patio
#

It shows a missing char after the key

#

Yep

#

I'm certain that it's TMP messing up

sleek bough
#

Then you just need to make sure UI element large enough to fit

pastel patio
#

TMP has missing char issues

#

Like trying to display A/u25A1

sleek bough
#

Test by putting text manually. UI has options that wrap text to next line that can obscure, etc.

pastel patio
#

U+25A1 is whitesquare

#

Which cannot be displayed

#

Showing a box

sleek bough
#

Ah, if it's a missing character you need to add it into font asset

pastel patio
#

Uhm no, that's not the case.

#

On Legacy text, it displays as A

#

On TextMeshPro text, it displays as A \u25A1

#

And on debug, it displays as A as well

#

Even if I added the character to the font, it's a character that wasn't supposed to be shown in the first place

unkempt pebble
#

hello, i am working with inventory and i have problem can someone help me? if you equip an item and then move the item in your inventory or drop it, it is still equiped

pastel patio
unkempt pebble
#

interesting

pastel patio
#

Unimportant for your usecase but I divide my inventory up into InventorySlotGroups

unkempt pebble
#

oh

pastel patio
#

Each slot group has an event telling slot changes, including change index

sleek bough
pastel patio
#

This one -> public Action<Itemstack, int> OnSlotModify;
Itemstack = The new itemstack
int = the slot index

#

There're legit many ways to do this tho, mine's just an example

static matrix
#

how could I detect if an object is "behind" another in 2d
like if I was to make a perpendicular line to an objects transform.up and check whether another object lay in front of or behind it

gray thunder
#

check layers

static matrix
#

????
how would layers matter, this is for position

gray thunder
#

ah

knotty sun
static matrix
#

well im aware of how I can check for in front or behind in general for 3d space
im looking for in front or behind relative to a vector

fleet tide
#

Hey !

So i have an problem when i build my game :

In unity, when i run, i spawn and everything is good

When i build, and start the game, i'm blocked in menu and i need to click on server and on client

Why and how to fix it ?

PS: I use Fishnet and PlayFlow

vagrant blade
#

Make a development build and look at the console for errors. Nobody can begin to 'why and how' fix this question with less information that you have.

fleet tide
#

This is the view in unity when someone launch the game but dont click on server and client :

knotty sun
#

do not cross post

#

then remove it from here

#

because people like you require it when they don't follow the rules

vagrant blade
#

This is a community server, the active community members know and help enforce the rules.

#

Don't be upset because you were told to also follow said rules. Crossposting is not allowed.

#

And no, visual scripting shouldn't have severe performance. It's just code in the end.

knotty sun
vagrant blade
#

Yeah, I don't actually know what happens behind the scenes

#

I'd assume it's not that big a difference. Or hope anyway, assuming you have a clean board

knotty sun
#

I've made node based systems and they are damn difficult to be made efficient

#

I will give the guys at Bolt the benefit of the doubt

thick terrace
#

unity visual scripting is all reflection-based, there's no codegen yet unless that changed in unity 6

#

there are third-party ones like unode that do codegen

knotty sun
heady iris
thick terrace
#

there is generated code as part of the package, but just node boiler plate for the editor iirc

heady iris
#

ah, like how code is generated for other graphs (to define the nodes themselves, that is)

thick terrace
#

yeah, the graphs themselves are just unity assets

heady iris
#

I remember seeing a Generated folder while helping someone with a weird shader graph problem

thick terrace
#

you might find it's not a problem for your game, like for my use case it's fine because we're not using it for anything high performance, just various simple game logic

#

if you do hit performance problems, i believe unode comes with a tool to convert unity visual script graphs to its own format, so you could maybe keep that as a backup option

serene stag
#

yes for some.

#

yes few new features applied.

heady iris
#

I guess I'd say it's composition-based.

#

You don't create more specific kinds of GameObject

#

you attach components to game objects

oblique spoke
#

Entities/GameObjects with components (EC) is probably the way to communicate it.

modest ether
#

Does anybody have experiences with builidng packages? I having a small roadblock and I dont know how to fix it. I know that my code works but when I want to create a package with it Im missing dependencies and stuff
I wanna make a package out of my custom Visual Scripting Nodes but Its like I cant use the using of Unity.Visualscripting inside the script

#

It works outside of the package just fine

heady iris
leaden ice
leaden ice
modest ether
#

yeah okay I think I did that for Mathematics

leaden ice
#

Yup, same process

modest ether
#

but there is no deffinition for Visual Scripting

leaden ice
#

Yes there is

modest ether
#

where?

modest ether
#

what?

#

thats all the defintions I have

leaden ice
#

Is the Visual Scripting package installed in your project?

modest ether
#

Yeah

leaden ice
#

As a package? Or as an asset in the asset folder?

modest ether
#

yes package

#

it works with the same script which is not inside the package

#

also I imported like the mathematics in the assembly definition so yeah

#

you mean this part right?

thick terrace
#

if for some reason the picker isn't showing it, you can probably drag and drop the asmdef from the visual scripting package into an empty slot in the list, or edit the asmdef as json and just type it in

leaden ice
#

Yeah that^

modest ether
#

its empty haha

#

for whatever damn reason

#

I just dont get it whats happening lol

thick terrace
#

well, there's your problem i think lol

#

🤔

modest ether
#

yeah but freaking why

thick terrace
#

maybe just reinstall it then

modest ether
#

its always installed

#

you cant remove it

thick terrace
#

is it installed as a dependency from some other package?

late lion
#

You can remove it, but it comes installed by default.

leaden ice
leaden ice
leaden ice
modest ether
#

wow I freaking hate the package manager

trim rivet
#

How can I get the distance between an object in the scene view and the scene view camera ? 👀

#

anyone know

modest ether
#

I just dont have it

#

I can use it

#

but I cant add the definition...

modest ether
#

Creating a new Project its there

#

why atwhatcost

#

anyway thanks for helping

#

I go the route with the new project

pliant sapphire
#

Hello guys I need help, I have this patrolling script in which enemy will go from point to point and when it comes to last point it will just stop. I want my enemy to go back to the first point and start looping and I also want my enemy to face where the point is because now he will just walk backwards to the point that is at the back of him for example. This is script: https://hastebin.com/share/abuwegolov.csharp

leaden ice
#

Use Debug.Log to make sure current = (current + 1) % points.Length; is running

pliant sapphire
#

Okay

#

it gives 0 @leaden ice

thick terrace
#

you're reassigning the value in the debug log with that, just do Debug.Log(current)

pliant sapphire
#

okay

pliant sapphire
#

idk how did he start looping now first 3 tries he didnt loop

glacial tundra
#

I haven't touched Unity in a while, but wanted to ask if Animator controller is only official path to animating sprites. It looks like the legacy Animation component doesn't actually change the sprite in SpriteRenderer any longer. Surely there is a better workflow for sprite animation that I'm just not seeing.

#

The goal for me is use a FSM to change out AnimationClips in script without the overhead, and potential runtime errors, of setting up states and transitions in the editor.

#

These AnimationClips are also getting AnimationEvents generated at runtime, so any method of assigning them would need to respect those events.

cold parrot
heady iris
#

It's a pretty neat package: you do all of your animation through code.

heady iris
cold parrot
#

Animamcer is a readymade solution that is built on top of playables, so are mechanim and timeline

glacial tundra
#

Thanks for the recommendation for Animancer. Playables seems super verbose for something as simple as changing the index of a sprite sheet over time.

heady iris
#

you could also just make lists of sprites :p

glacial tundra
#

Yeah, it's hard to understand how something as simple as an out of the box 2d animation system doesn't exist.

#

The Animation component of old was really straightforward.

cold parrot
heady iris
#

the out of the box 2D animation system is the Animator

glacial tundra
sacred pewter
#

and anything beyond animator but not quite mechanim is best done DIY in 5 lines of code

heady iris
#

yes, it plays animations

#

and you can animate a sprite renderer's sprite

oblique spoke
sacred pewter
#

it still is and its not even deprecated

glacial tundra
#

I'm in 2022.3.20f1

#

Also running Debian editor, but I haven't seen any runtime issues because of Linux. There are some editor bugs.

glacial tundra
#

I honestly thought Animator and Mechanim were the same system.

#

Based on the documentation, it seems they are anyways.

glacial tundra
cold parrot
#

why don't you just make animation clips from your sprite sheets, put them in an animation component and activate/play the animation you want in a script?

glacial tundra
cold parrot
#

an animation clip change is nothing more than an instant blend

glacial tundra
#

I'm not sure how to say it any differently than the legacy Animation no longer works with sprites.

#

You can make the clip, mark it as legacy, and attempt to play it with a sprite renderer attached and it will do nothing.

heady iris
#

you could just use an AnimatorOverrideController to swap out animation clips

glacial tundra
gray mural
#

Hey, is there any way to simplify it using a single StartSomething method without it being async?

private void StartSomething(IEnumerator coroutine) => StartSomething2(coroutine);

private async void StartSomething2(IEnumerator coroutine)
{
    await MyTask(coroutine).ConfigureAwait(false);

    test = false;
}

private async Task MyTask(IEnumerator value) { ... }
thick terrace
chilly surge
#

Use ContinueWith.

gray mural
gray mural
thick terrace
gray mural
heady iris
#

there's this fella

#

I have not used it before

gray mural
heady iris
#

cries

chilly surge
thick terrace
#

there should never really be a need to use ContinueWith tbh, async does more or less the same thing with much better defaults

chilly surge
#

But honestly this code looks kind of weird so I'm not sure what the point is.

gray mural
glacial tundra
#

Is this for an editor tool?

heady iris
#

there's no real consistent update cycle at all, is there

#

The iterator functions passed to Editor Coroutines do not support yielding any of the instruction classes present inside the Unity Scripting API (e.g., WaitForSeconds, WaitForEndOfFrame), except for the CustomYieldInstruction derived classes with the MoveNext method implemented

#

sad

#

I presume that a custom yield instruction would only get MoveNext called whenever the editor decides to update

gray mural
chilly surge
#

It's never called?

gray mural
chilly surge
#

But you can see the error being written to console right?

gray mural
#

No, I don't see the error in the Unity console

#

It's just that the method stops from its execution

thick terrace
#

does Console.WriteLine do anything in unity? surely you want Debug.Log

gray mural
#

When using the initial approach, it does stop, and the error is thrown

gray mural
#

My bad

#

It does print the exception to the console, still, no exception is being thrown when done this way

MyTask(coroutine).ContinueWith(t =>
{
    print(t.Exception);

    throw new(t.Exception.Message, t.Exception);
},
    TaskContinuationOptions.OnlyOnFaulted);
chilly surge
#

You can just throw it yourself or do whatever handling with the exception directly, no?

#

I mean, ultimately async/await just compiles to a state machine, so at worst you can just look at the compiler output and copy it.

#

(The whole use case still feels very weird to me though)

waxen blade
#

I have a class with a bunch of different Vector3s, and I want to consolidate it into a single class. However, when I do that, I don't now how to add it into a dictionary.

public class Foo
{
    public class Bar
    {
        public int TestInt { get; set; }
        public string TestString { get; set; }
        public TestPositionData MyPosition { get; set; } = new TestPositionData();
    }

    public static Dictionary<int, Bar> Bars = new Dictionary<int, Bar>()
    {
        { 1, new Bar{ TestInt = 1, TestString = "A", MyPosition.???} },
        { 2, new Bar{ TestInt = 2, TestString = "B", MyPosition.???} }
    };
}
public class TestPositionData
{
    public Vector3 PositionA { get; set; }
    public Vector3 PositionB { get; set; }
    public Vector3 PositionC { get; set; }
}

TestInt and TestString have the correct snytax when adding it to the dictionary. How do I set MyPosition.PositionA, MyPosition.PositionB, and MyPosition.PositionC directly into the dictionary?

heady iris
#

you would need to construct a new TestPositionData there

#

somethingl ike MyPosition = new TestPositionData() { PositionA = Vector3.one }

waxen blade
#

Now I'm just trying to get the syntax on your suggestion correct.

heady iris
#

Not enough closing braces

waxen blade
#
    public static Dictionary<int, Bar> Bars = new Dictionary<int, Bar>()
    {
        { 1, new Bar{ TestInt = 1, TestString = "A", MyPosition = new TestPositionData() { PositionA = new Vector3(0, 0, 0)  } } },
        { 2, new Bar{ TestInt = 2, TestString = "B"} }
    };
#

I think I got it.

#

Thank you Fen. 😃

heady iris
#

Also, you should be able to omit the type name

#

so just MyPosition = new() { ... }

waxen blade
#

Yeah, it's already cluttered enough as it is so I'll get rid of that.

fallen ridge
#

Any reason why line 71 would return the Element 5 on the first iteration of the for loop?

heady iris
#

you are modifying the prefab itself

#

that seems weird

#

You're throwing out the new instance

#

it it going bye-bye

#

I bet you draw six cards

fallen ridge
#

I'm not gonna lie idk what im doing here

#

its drawing the 5

heady iris
#

you're seeing the card that you wrote into cardPrefab in the last iteration of the loop from the last time you ran it

#

(okay, if we're 1-indexing, then you're drawing 5 cards)

rigid island
heady iris
#

You should store the return value from Instantiate and modify that

rigid island
#

modify the copy

fallen ridge
#

I'm loading the prefab with new info

heady iris
#

And it's producing nonsense results

#

You need to modify the new instance

fallen ridge
#

ahhhhh

#

i shall return in a timely matter

#

I'll probably rename newCard at some point but this worked. thank you 😛

wary dock
#

Heya. I would like to make prototype of games like They Are Billions. Any advice on the approach I can take for having potentially thousands of units on screen with collision and such? I recently started checking out DOTS but are there other approaches?

heady iris
#

I need to try that out myself

#

One thing to consider is to manually draw the enemies instead of using a crapload of individual MeshRenderers/SpriteRenderers

#

oh wait,

#

I am not very experienced here, though.

leaden ice
#

Also I love that game glad to see it mentioned

heady iris
#

I experimented with a "3 bajillion enemies" game with DOTS

#

the player was 100% normal GameObjects

gray mural
gray mural
#
private async Task MyTask(IEnumerator value)
{
    while (value.MoveNext())
    {
        if (value.Current is IEnumerator enumerator)
            await MyTask(enumerator);

        await Task.Delay(20);
    }
}
timid meteor
#

Having some coding issues atm with this code. The Error I am getting is sthis

#

Trying to make some grass atm

rigid island
gray mural
rigid island
#

what is : supposed to do ?

timid meteor
#

Yea I am trying to do gpu instancing for grass

gray mural
#

I guess : is used in a foreach loop for some languages as in in C#

rigid island
#

have you used a List before ?

timid meteor
#

not really in the dark with this mostly

rigid island
#

you need the instance in the list " Batches"

#

loop over that

gray mural
#

So you can just call 2 loops

leaden solstice
#

So just do foreach (var batch in Batches)

timid meteor
#

would that work?

#

for peformance reasons

leaden solstice
#

Performance for what?

gray mural
#
foreach (List<Matrix4x4> batch in Batches)
{
    foreach (Matrix4x4 matrix in batch)
    {

    }
}
Batches.ForEach(b => b.ForEach(m => 
{

}));
timid meteor
#

I am trying to load a ton of grass in a scene

leaden solstice
#

What does that suppoused to do with syntax error

rigid island
#

maybe start with like pong or something

#

if you don't know c# syntax

simple egret
#

I think they're mixing it up with languages that put the type after the name in declarations
Like let x: int32 = 45

rigid island
#

go?

simple egret
#

idk, I made that syntax up, but it surely exists somewhere

rigid island
#

oh wait go doesn't use :

#

var b, c int = 1, 2

#

Unity Cloud server functions API uses Go notlikethis

fervent furnace
#

typescript/rust/python iirc

leaden solstice
#

Rust but with i32

fleet tide
#

Hey ! i would like to, create an updater but how can i do that if i want remplace every file even the executor ? (like an self update) In this way, with 1 download, we can have always the latest version

rigid island
#

You'd have to handle things like files while in use

fleet tide
#

maybe I was thinking of creating a temporary file to run code

rigid island
#

thought you were making an updater app separately than unity

#

btw if you use addressables you can just replace specific files instead, no need to update the whole build

fleet tide
rigid island
#

no you stream the update to the game launcher

#

ideally with an API call to your versioning

#

making a launcher, especially a bad one might deter players so be careful with that

fleet tide
#

So i can create an Game Launcher who can update itself by an API and update the game ?

rigid island
#

yes of course

#

anything can be coded

fleet tide
#

Interesting ! I wanted create a game launcher but i trought is was better to have it in my game

rigid island
#

if you do it in-game go with the addressables maybe

fleet tide
#

I never use addressables but i will learn 🙂

#

thanks sadok

fleet tide
#

Thanks for the link ! blushie

rigid island
fleet tide
#

for now, its a very light game so its more for later ^^

lament helm
#

has anyone coded an rpg?

#

pokemon style combat

pastel patio
#

Hi guys, how is input rebinding intended to be used? The rebinding sample changes the binding referenced by an InputActionReference, I don't understand how this works

pastel patio
#

The input I created elsewhere isn't the one referenced thus leading to the rebinding to apply to an unused instance

#

Is there a specific instance that the InputActionReference points to that I can find? Was I meant to use that one?

pastel patio
#

Oh... I thought that this one counts as programming related

#

Sorry

rigid island
#

input system covers both

lament helm
rigid island
pastel patio
#

These kinda stuff has too many ways...

rigid island
# lament helm yes

thats something you can easily google, cause as mentioned above there are dozens of ways to accomplish something

#

you have an easier time getting help on a specific part of code you're stuck on

lament helm
#

understood

heady iris
#

I am rewriting my "IK Manager" class. It's going to support multiple different IK components, and different kinds of components are identified differently

#

For example, a generic chain IK is just going to be identified by the last bone in the chain

#

there's also a full-body biped IK component that controls all of the limbs, and so I identify which limb I'm moving with an enum

#

so right now I've got this, basically

#
public void SetTarget(FullBodyBipedEffector effectorID, Transform target)
{
    if (bipedIKControlMap.TryGetValue(effectorID, out var controller))
        controller.SetTarget(target);
}

public void SetTarget(Transform tipBone, Transform target)
{
    if (chainControlMap.TryGetValue(tipBone, out var controller))
        controller.SetTarget(target);
}
#

This is fine.

#

However, I'm finding it annoying to allow other components to flexibly use both kinds of IK

#

I have a component for pulling a lever. For a humanoid, it wants to use a full body biped IK's right hand. For a non-humanoid, it will need to use a different kind of IK to control a robot arm or whatever

#

I need to be able to configure both kinds of IK interaction on this "pull lever" component

#

I had the thought to just do this:

#
[System.Serializable]
public abstract class IKSelector : IPolymorphic
{

}

[System.Serializable]
public class FullBodyBipedEffectorIKSelector : IKSelector
{
    public FullBodyBipedEffector effector;
}

[System.Serializable]
public class TransformIKSelector : IKSelector
{
    public Transform tipBone;
}
#

and then...

#
public void SetTarget(IKSelector selector, Transform target)
{
    if (selector is FullBodyBipedEffectorIKSelector fullBodySelector)
        if (bipedIKControlMap.TryGetValue(fullBodySelector.effector, out var controller))
              controller.SetTarget(target);

    if (selector is TransformIKSelector transformSelector)
        if (chainControlMap.TryGetValue(transformSelector.tipBone, out var controller))
              controller.SetTarget(target);
}
#

and I...guess this works? it just feels kind of weird

#

this is a lot like making an algebraic datatype in a language like Haskell though

heady iris
fleet tide
#

@gray mural

Update ^^: I have setup the server and the client.
Now we can play with other player on the map like a real MMO ^^ I need to work on spawn mob and all mechanics about it ^^

pulsar holly
rigid island
#

Nuke the code, start over with something that makes sense

#

don't write redundant WET code

#

You ended up not understanding your own code, thats how you know is especially bad if you've written it yourself

lean sail
#

I tell so many people this, you'll waste HOURS debugging complete garbage code, compared to just learning how to properly code in those few hours and having something decent

#

Although really, we also know you havent debugged anything in there, even though it's been suggested before.

#

The sunk cost grows and grows

spring creek
#

I have completely restarted projects far further along than this multiple times. Or reverted to an earlier state MANY times.
That is part of progress.
Can't be afraid of restarting

uncut palm
#

anyone ever had the issue with nav mesh agent where setting the destination immediately teleports the agent there? even on a blank test script (with the speed at 2) it just warps immediately

heady iris
#

maybe you have similar problems

#

I'm not aware of anything that'd cause this, though

uncut palm
#

ill move there

pulsar holly
dusk brook
#

Guys this may be a stupid one but I have both

using UnityEngine;
using UnityEngine.SceneManagement;

however I am getting SceneTools does not exist in the current context

#

Was it removed in 6.0?

leaden solstice
#

What is SceneTools, I don’t think that was ever a thing

storm wolf
#

Do you mean SceneManager?

simple egret
#

Nothing relevant for SceneTools on Google, maybe you had a package or custom assembly installed?

dusk brook
#

Perhaps, I'll have a dig

#

Thanks

storm wolf
#

Definitely not part of unity

opaque forge
#

Hello, I have a problem which I'm trying to solve which I thought I could use Physics.Raycast for, and I don't get why my approach is not working :
I'm generating a bunch of tiles with edges surrounding them, but for some cases it generates incorrect tiles, so I delete them under a certain condition. However I have
the edges surrounding the deleted tiles present in the scene, and I want to delete edges that are not surrounding anything. The solution I thought about is to use Physics.Raycast on both side of each edge to perform a check if it's enclosing a tile (I attach a collider to all tiles). For some reason, as you can see on the picture above, it works in most cases but there are a few edges that are not deleted and I don't understand why, it's seems that the raycast detects something even though nothing is there

heady iris
#

notably

#
var tile = Instantiate(myPrefab, Vector3.zero, Quaternion.identity);
tile.transform.position = Vector3.right * 100f;
Physics.Raycast(Vector3.up, Vector3.down, 100); // this hits the tile!
#

Calling Physics.SyncTransforms(); gets everything up to date

opaque forge
#

I set up automatic physics sync transforms in the settings but I'll check with this again

heady iris
#

i forgot about that!

opaque forge
opaque forge
heady iris
#

Because if you instantiated your hexes and then moved them, they'd all be left at [0,0,0] in the eyes of the physics system

opaque forge
#

wait I'll check the settings

heady iris
#

(or wherever the hexes appeared at)

opaque forge
#

the weird part is that some edges do get deleted like they are supposed to so I think it's got smth to do with the physics system

heady iris
#

are you drawing a red ray when it misses?

#

if so, the raycast is working fine

#

oh, they're all red

#

i'm bad with red and green

#

Try making it draw a different color if the raycast hits

#

that will reveal if it's a bug with your logic afterwards

opaque forge
#

yeah maybe raycasting is not suitable in my case where everything is done in the start frame

heady iris
#

Consider logging what you're actually hitting

dapper schooner
#

Does anyone here know if Shadergraph Fullscreen shaers work on mobile?

#

Quest to be speific

opaque forge
swift falcon
#

lads

#

in this current economic climate

#

is it really worth getting unity?

vagrant blade
#

Instead of baiting with a vague open ended question, maybe explain what you're worried about?

weak venture
lament patio
#

Hey, i have a Problem with my Character Controller. When i'm Jumping while Moving im Jumping slightly lower than if i'm standing still. Does anybody know why this happens?

    {
        
        if (movement.y > 0)
        {
            Vector3 dir = playercamera.transform.forward;
            dir.y = 0;
            force = force + dir;

           
            //m_Rigidbody.AddForce(dir.normalized * speed);
        }

        if (movement.x < 0)
        {
            Vector3 dir = playercamera.transform.right;
            dir.y = 0;
            dir *= -1f;
            force = force + dir;

            
            //m_Rigidbody.AddForce(dir.normalized * -1f * speed);
        }

        if (movement.y < 0)
        {
            Vector3 dir = playercamera.forward;
            dir.y = 0;
            dir *= -1f;
            force = force + dir;

          
            //m_Rigidbody.AddForce(dir.normalized * -1f * speed);

        }

        if (movement.x > 0)
        {
            Vector3 dir = playercamera.transform.right;
            dir.y = 0;
            force = force + dir;

           
            //m_Rigidbody.AddForce(dir.normalized * speed);
        }

        if (doesjump > 0f && Jump)
        {
            Vector3 velocity = m_Rigidbody.velocity;
            velocity.y = 0;
            m_Rigidbody.velocity = velocity;


            m_Rigidbody.AddForce(transform.up * height*50f);
            Jump = false;
        }

        m_Rigidbody.AddForce(force.normalized * speed);
        force = new Vector3(0f, 0f, 0f);
novel dagger
#

am i allowed to copy paste a full reddit post describing my problem or should i just link the thread. trying to get help asap lol

spring creek
novel dagger
#

i think i explained it concisely in the post and i tried to explain what i think is wrong and how i tried to fix it

#

feel like i’m missing something fundamental

#

i have a rope linking a player and a collider, the rope should stretch if the player moves away from the max distance but the rope isn’t stretching or growing despite the fact that my debug statements somehow say it’s moving further away (even though it’s physically in the same place)

mortal pond
#

It's some boiler plate code I found that I need a small change too

#

right now it creates a seperate scene and loads that, but this doesn't work for my use case of multiplayer scene management, so I need someway to just basically import the asset/scene into my current/main scene

void wedge
#

is there just a general help channel? Im trying to fix my slider UI

#

my health bar slider is starting at the edge but when it reaches value of 1 (full) it sits in the right spot?

frosty widget
#

I have a question for those that are familiar with unity's physics system, particularly with the drag value of RigidBody2D. In my InAirState script, I am capping the horizontal velocity of my character whenever it reaches it's max speed. However, drag is reducing the value that I have set at the end of FixedUpdate, to a value below the max. A solution to this issue would be to set the drag to zero, but this makes my jumps higher than intended. Is there a way to solve this issue without reducing drag? Here is my script and some related ones https://gdl.space/niyeqoyohi.cs, https://gdl.space/kigoxizevi.cs, https://gdl.space/udolejurep.cpp

mortal pond
#

which one is health the red green or blue

void wedge
#

the red is the health bar, The green and blue bar are sitting in the correct spot (because I havent added slider to them yet). I want the red bar to start and end where the other bars are

mortal pond
#

is this the issue

#

check for padding settings

void wedge
#

yea its just being pushed back instead of starting where it should. As the value increases the health bar moves into its correct place where the others are

mortal pond
#

did u make a direct copy of the other ones and then move it up and change color

void wedge
#

ive got the fill color set to stretch

#

I made the health bar first and copied the other 2 from that, but those dont have sliders on them yet

#

When its on max value its in the correct spot but idk why its out of position when it starts

versed marsh
#

how do you create these types of UI elements again? If I'm remembering correctly there is a class that allows you to create very simple UI like this in code, but Im forgetting what its called and cant find it online.

spring creek
#

There is UGui, and UIToolkit. You can do both in code really, but UIToolkit uses language like html and css (uxml and uss).

That being said, I would not call that a simple ui. Lots of logic involved in that, rather than just showing values

rigid island
#

Ideally you should use the Canvas / UI Toolkit

#

these are only okay for testing

versed marsh
#

ahh okay, didnt realize it was depricated. The only reason Im trying to use it is since Im making a mod for another game and just needed a very simple ui button

frosty widget
#

Does anyone know an equation to handle drag in the same way that unity does?

#

I googled it and tried out RB.velocity **= 1/(1 + Time.fixedDeltaTime * * dragValue ), but this formula didn't work

lean sail
torpid depot
#

guys ı got a questıon

#

anyone have any advıce for some tutorıals?

#

a good ones

rigid island
tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

rigid island
#

start with pathways

torpid depot
#

!learn

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

torpid depot
#

oh

#

okay ty

dusk apex
#

You'd probably want to provide more information like the code for instance.

lean sail
#

look at the #854851968446365696 on what you should include in questions. We'd need to see more of the setup like code, how you pick up items or drop them. I assume you duplicate the item

#

!code the readme also says the same for large code blocks. Though really, you should narrow it down to a related sections. posting it all in a link is fine, if you at least say where to look and whats relevant. not many people are gonna read through that much code

tawny elkBOT
unkempt pebble
#

nvm i fixed it

edgy bough
#

Hey, what could be the reason of my Header attributes not showing in the editor?

#

The Inspector isn't set to Debug mode

edgy bough
#

Not sure, the class is derived from FishNet's NetworkBehaviour, so that might be the issue

timid briar
#

I need a enemy follow player script

gray mural
# timid briar I need a enemy follow player script
using UnityEngine;

public class EnemyController : MonoBehaviour
{
    private void Update()
    {
        if (Physics.SphereCast(transform.position, float.MaxValue, 
            transform.forward, out RaycastHit hitInfo))
            transform.position = hitInfo.transform.position;
    }
}
barren elbow
#

Hello everyone! My VS 2022 has stopped autocompleting when I press tab. It instead cycles through selectable things. Intellisense does work, it suggests code.

dry sleet
#

Hey guys,
I'm implementing fishing system. I have characters animations for fishing and rod animations separately.
Does it make sense to use separate animators on each with same states and transitions and just set triggers or bools for transiting between them ? Will they be in synced ? (Animations length are same in both the rod and the character for the each kind of animation)

rain junco
knotty sun
rain junco
#

i logged the name before in the foreach loop

#

it tells me the second element then this

knotty sun
#

The error does not match your code but assiming line 103 is line 102 it means item is null so you have a null item in your array

rain junco
#

but idk why

rain junco
knotty sun
#

that is why we debug. Add a null check

cosmic rain
#

Might also want to print the name of the object that the code runs on

solid rivet
#

hello guys. I have a problem. I have a unity project and i dont konw how to setup a click event, because the design has changed from unity itself. I have 2 images and i want to have it like the old design (marked with red). Someone can help me with it?

cosmic rain
# rain junco why that

Because you might have this script running on some other object that has a null reference in the array

rain junco
#

doing now

#

foreach (var item in iconList)
{
if (item == null) Debug.Log("An item is null" + gameObject.name);
}

#

no other object

#

is there a problem with an in inspector assigned list?

cosmic rain
#

Then the item is null

knotty sun
#

try logging the index of the item

cosmic rain
#

Not necessarily. It could be null temporarily for example.
Ideally you want to step through with a debugger

rain junco
#

i just noticed they got reset when starting, didnt happen before

cosmic rain
knotty sun
#

your code does have this in Start.
iconList = new PickaxeIcon[iconList.Length];
that's why

rain junco
solid rivet
cosmic rain
solid rivet
#

no i had it in debug mode hahah

#

i love you so much bro thanks a lot

dusky niche
#

sword.transform.parent = transform.GetChild();
if the child is also a parent then would it work if I put the total index number of the child inside the transform?

knotty sun
#

what are you trying to do, because that is invalid code

dusky niche
#

trying to make an object as child of another object

knotty sun
#

I know that, but which child should become the parent?

dusky niche
#

sword is an inherited gameobject
Trying to become the child of the object this script is attached in

knotty sun
#

then why GetChild ? just use transform

dusky niche
knotty sun
#

i think you are misunderstanding

sword.transform.parent = transform; // set sword as child of transform
sword.transform.parent = transform.GetChild(0); // set sword as child of child zero of transform. (Grandchild of transform)
dusky niche
#

I mean make the child inside the child as parent

knotty sun
#

what?

dusky niche
knotty sun
#

presuming you just forgot to mention the 001 bit of the names

sword.transform.parent = transform.GetChild(0).GetChild(0);
dusky niche
#

I see thx

knotty sun
#

you do realize this will go bang if those children don't exist or are organized differently

heady iris
#

it would be significantly better to store a reference to the transform you're attaching the sword to

#

rather than rooting around in the hierarchy like you're mining for coal

hard tapir
#

which script is more performant? ```
using UnityEngine;

public class Script1 : MonoBehaviour
{
private Manager manager => GetComponent<Manager>();

private void Update()
{
    if(manager.b != null)
    {
        mananager.b.Func();
    }
}

}

using UnityEngine;

public class Script2 : MonoBehaviour
{
private Manager manager => GetComponent<Manager>();
private B b;
private void Awake()
{
b = manager.Resolve<B>();
}
private void Update()
{
if(b != null)
{
b.Func();
}
}
}

using UnityEngine;

public class Manager: MonoBehaviour
{
public B b;
}```

cosmic rain
#

The second one, since the first one calls GetComponent every frame. But the difference is probably not very noticible.

gray mural
#

Hello, just to make sure. These 2 variants do have 1 frame difference in in time, right?

WaitForSeconds(2f);
WaitForSeconds(1f);
WaitForSeconds(1f);
#

So Unity doesn't call the 2nd IEnumerator in the same frame when the 1st's MoveNext returns false, it waits a frame instead?

leaden ice
#

more than one frame

gray mural
leaden ice
#

WaitForSeconds waits until the next frame after N seconds have passed

gray mural
#

Why would the difference be more than 1 frame though?

leaden ice
#

So you'll get like:
2.01 seconds (assuming frame error of .01 second)
vs
1.01 + 1.01 seconds

#

well one thing also is that frames are not consistent durations

gray mural
#

I see, I wasn't assuming the errors

leaden ice
#

so if the frame error for the first wait is longer than a later frame, it could be 2 or more frames

gray mural
#

The 2nd variant should get 1.01 + 0.01 + 1.01 this way though

leaden ice
#

It just depends on the luck of where the frames land basically

gray mural
hard tapir
#

because script 2 gets B just once right?

gray mural
hard tapir
#

in script 1 it gets that B through manager but every frame

gray mural
leaden ice
gray mural
hard tapir
#

so conclusion is that script 2 is better? => storing local variable and then get it once is better

gray mural
#

But regardles of B staying the same or not, b stays the same

gray mural
hard tapir
gray mural
#

And it would be better to simply remove the property

#

As I don't see whether you need it

cosmic rain
#

I'd disagree about the "much worse". It is worse, but the impact this one difference would have is probably barely noticeable if at all.
Not saying that you should use the first variant. You should definitely cache your references whenever possible. But it's important to understand that it's not gonna explode your game.

spring creek
#

I would move away from using OnCollisionEnter and OnCollisionExit for ground checking. What if your head hits the ceiling..

Oh, and its gone

leaden ice
maiden heath
#

that should solve it

spring creek
maiden heath
# spring creek Ah gotcha. So the code you showed is two scripts?

https://pastebin.com/f8DLrzKM this is the groundcheck script
https://pastebin.com/g4PgLBKJ this is the player script

gray mural
spring creek
#

Yeah, that works then, and avoids the issue I mentioned

gray mural
maiden heath
#

will do in a sec

cosmic rain
#

Unless you jump high enough to clip through the ceiling and getting stuck in it, since it will be considered grounded

maiden heath
glacial tundra
gray mural
# maiden heath i updated it now

I would have a reference to your feet in the PlayerMovement script, and add the GroundCheck script to it in Awake.

private void Awake()
{
    GroundCheck groundCheck = feet.AddComponent<GroundCheck>();
    groundCheck.playerMovement = this;
}

Then assign its playerMovement reference and access isGrounded and groundLayer from it.

private void OnCollisionEnter2D(Collision2D collision) => SetGrounded(collision, true);

private void OnCollisionExit2D(Collision2D collision) => SetGrounded(collision, false);
 
private void SetGrounded(Collision2D collision, bool value)
{
    if (collision.layer == playerMovement.groundLayer)
        playerMovement.isGrounded = value;
}
maiden heath
sleek heath
gray mural
cosmic rain
hard tapir
#

Because more and more code there is the more confusing it gets

eager steppe
#

!code

tawny elkBOT
eager steppe
#

alr bet

#

Hey everyone! Trying to be able to get a variable FROM a class by name rather than hardcoding shit and it be a pain (so, like if i called GetVariableByName(keyName, className), the class i'm trying to find is what 'className' is, and the variable i'm tryna find is what 'keyName' is.)

Alright so here's the whole script: https://hastebin.com/share/ubexozaqob.csharp

But any time i call GetVariableByName() it comes back as null - i would search as to why but to be honest I have no idea what I'm doing or why i wrote what i wrote. I'd love to know how or why what i did is not doing what its meant to did
if you need more info do let me know

cosmic rain
#

I'm not going to say that if you're gonna use that widely in your project as a replacement to normal accessing methods, it's gonna be terrible. I assume you know it and have a specific use case.

eager steppe
gray mural
cosmic rain
eager steppe
eager steppe
gray mural
maiden heath
simple egret
# eager steppe enters the first property check

None of the classes posted here actually have properties in them, they're all fields. So GetProperty() won't be finding anything. For reference, a property declares accessors:

public int SampleProperty { get; set; }

What you have don't have accessors, so they're all fields

eager steppe
dusk brook
#

Which UnityEngine class would a Panel come under?

#

Just GameObject?

cosmic rain
dusk brook
#

And GameObject doesn't even work

cosmic rain
dusk brook
#

Simply the size of it is all I want

#

Dynamically

heady iris
#

you can reference its RectTransform.

cosmic rain
#

Not sure what you mean by size of it, but GameObject should work as a reference

dusk brook
cosmic rain
#

Is that a serialized field?

dusk brook
cosmic rain
#

What type does it have?

dusk brook
#

GameObject

cosmic rain
#

Share the code

dusk brook
dusk brook
#

It's in a ScriptableObject

cosmic rain
#

You can't reference scene objects from outside the scene.

dusk brook
#

Sounds logical yup

#

Thanks

dusk brook
cosmic rain
#

Your code should be in the scene as well

#

Can't say anything else without knowing the context

dusk brook
#

My simulation code is in the scene, as a script, I'm just wondering what kind of box/container is used to manage components that can be resized

limpid agate
#

Hey guys, any idea why in the game view (using the camera), the line renderer doesn t render some parts of it, while in the scene, it s perfectly fine?

dusk brook
cosmic rain
#

Well "components that can be resized" is a very vague definition. What component exactly? Are they ui Image components?

dusk brook
#

Bear with me, I'm trying to comprehend this myself

#

Here I have a panel (green) representing the simulation field - I want to be able to get the size of this panel, and to be able to resize this panel as well

#

The panel contains 2d game object organisms

cosmic rain
tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

cosmic rain
#

Also, you might not need help at all if you do proper learning. Killing 2 stones with one bird

dusk brook
#

The dissertation is like 90% theory and neural network but ultimately I'm spending all my time trying to build a graphic for it

cosmic rain
#

It's not really steep. You just need to spend a day or two on learning the basics of working with the engine(assuming programming is not an issue).

#

You can't jump into a professional software and hope to get something working of it by randomly pushing buttons. That's not how it works.

gray mural
#

Does Unity still wait for 1 frame after moving through all IEnumerators in a Coroutine when no MoveNext is available?

WaitForSecond(1f);
WaitForSeconds(1f);
// 1 frame
// stop
knotty sun
#

which, tbh, if you are doing anything with Neural Nets, you should already know

dusk brook
heady iris
#

At that point MoveNext will return false

#

I'm not really clear what you're asking about here, though

gray mural
dusk brook
gray mural
heady iris
#

show me the code you're actually running

heady iris
gray mural
#

It checks whether WaitForSeconds has finished executing by calling its bool MoveNext every frame

rigid island
knotty sun
rigid island
#

but yeah unclear what you're even going for here or what problem you're experiencing

cosmic rain
gray mural
#

Unity is not precise

dusk brook
gray mural
#

No MoveNext is called in this case when you're doing nothing in Editor

heady iris
#

i still don't understand what your problem is or what you're asking about

cosmic rain
#

There are editor coroutines package btw. For editor coroutines

knotty sun
cosmic rain
#

You don't really need to get into the guts of the coroutines. All you need to know is that it would resume on the first frame when the condition is satisfied

gray mural
simple egret
#

If MoveNext was called every frame, it would resume the coroutine and run it to the next available yield each frame. It waits until the second has passed before calling MoveNext again

gray mural
rigid island
candid elm
#

is it coding, sons

heady iris
rigid island
knotty sun
rigid island
#

so apparently all yeilds wait for the Update to finish

dusk brook
gray mural
rigid island
#

you can see where the yield run

simple egret
#

Yep that's the custom one

#

Regular ones are polled less frequently

rancid frost
#

mesh renderer sorting layer not working?

White square sprite and green square mesh are on thesame sorting layer but different order, but still they intersect. Why?

simple egret
rancid frost
heady iris
rigid island
cosmic rain
rancid frost
rigid island
#

yeah not sure layer order would affect the scene view

heady iris
gray mural
rigid island
rigid island
#

ohh its meshes?

#

then Order In Layer will not affect it

#

Mesh Renderer doesn't care about that only sprite renderer

gray mural
simple egret
heady iris
rancid frost
heady iris
rigid island
cosmic rain
#

You can make the scene cam orthographic too

rancid frost
#

I want to have multiple meshes ontop one another

rigid island
#

are they sprite renderer or mesh render ? im confused

rancid frost
#

the white square is sprite renderer, the green mesh is mesh renderer

rigid island
#

ohh

#

cause its trickier to sort 3D materials

cosmic rain
#

You should just position one in front of the other.

rigid island
#

i believe thereis a render order on the shader though

rancid frost
rigid island
#

yes

#

use the Z position to sort

rancid frost
#

will culling still take place?

heady iris
#

culling is frustrum-based (i.e. based on what's on the screen)

#

well, there is also occlusion-culling

heady iris
#

but that is baked in advance for static geometry

gray mural
# heady iris

I see, so it stops right after the IEnumerator is finished and doesn't wait for 1 more frame. This clears the things up for me, thank you

heady iris
#
    public IEnumerator CoroutineMethod()
    {
        Debug.Log(Time.frameCount);
        yield return StartCoroutine(AnotherMethod());
        Debug.Log(Time.frameCount);
        yield return StartCoroutine(AnotherMethod());
        Debug.Log(Time.frameCount);
    }

    public IEnumerator AnotherMethod()
    {
        yield return null;
        yield return null;
    }
#

Ah, it makes sense because Unity is not doing this:

  • check if CoroutineMethod can resume
  • advance AnotherMethod

It's just advancing AnotherMethod, and the moment it's done, it advances CoroutineMethod

gray mural
#

Do Unity's Coroutines use async?

rancid frost
heady iris
#

No, they don't use async at all

#

There is Awaitable (2023.2+), which lets you handle async methods more like coroutine methods

#

I'm still a bit unclear on the technical details of async.

gray mural
#

Is it's 2023.2+, then Unity's Coroutines surely don't use it

rigid island
#

depends what you're going for, the smallest number could potentially be all you need anyway

rancid frost
#

roger, thanks!

cosmic rain
#

Just note that some platforms might behave differently and need a bigger distance.

#

Otherwise there might be z fighting.

heady iris
#

The closer your near and far clip planes are, the closer you can place objects without getting z-fighting

#

(of course, that means you have less space to place your objects!)

#

you can't cheat the system (:

tawdry fox
#

My brain can't syntax right now but I feel like this is where I'd put a check for a coyote timer right??

#

Feels like it should be obvious but I've been using Godot for the better part of a year and kinda forgot.

vivid halo
#

I know you didn't ask, but two points of advice:

  • Curly braces should generally be on the same line for readability
{
  // Code
}
  • Enumerations should be used for integers that represent stages, such as jumpPhase = 0. Instead, it could read if (jumpPhase == JumpPhase.PreJump) or if (jumpPhase == Jumpphase.MidAir
leaden ice
#

Enumerations* aka enums

vivid halo
#

Oops yeah, correcting

leaden solstice
#

I think jumpPhase is counter here

#

How many mid-air jumps you performed

lean sail
vivid halo
#

It's absolutely readability, but it's also convention.

lean sail
#

Nope, 0 readability aspect to it. It's simply more or less readable because you are used to it. I find same line completely unreadable these days, because I do next line. In uni I used languages which did it on the same line, at the time I thought it was readable

vivid halo
#

In University I used

public void Example() {
  // Code here
}

And I was used to it, but it is simply less readable than matching braces.

leaden solstice
#

Readability as in consistency 😄

vivid halo
#

Matching blocks of code requires scanning side to side instead of simply following the vertical space down. Largely preference, but readability is a non-zero factor.

lean sail
#

Unless you do a case study where you ask random people which is more understandable, theres no debate about it. It's simply just what you're used to, because it's where you subconsciously expect it to be

tawdry fox
#

Anyways I appreciate the input.

leaden solstice
#

Almost all C# libs uses Allman style so you might as well too
If you are writing in Rust or Java that's different story

vivid halo
#

I was used to K&R first, and forced to adapt to Allman style, allman is more readable. Seems nonsensical to argue that K&R is more readable

public class ExampleClass {
  public void ExampleMethod() {
    if (condition1) {
      for (int i = 0; i < 10; i++) {
        while (condition2) {
          if (condition3) {
            DoSomething();
          } else {
            DoSomethingElse();
          }
        }
      }
    } else {
      AnotherMethod();
    }
  }
leaden solstice
#

That is unreadable, no matter what indentation style you use 😄

vivid halo
#

Is a poll required?

#

It's complex and not readable by baseline, but using Allman is very clearly a better choice for something like that.

lean sail
#

No, and I'm not claiming either is more readable. That is your claim. I am saying it's your preference, and generally you shouldnt enforce code style here. Conventions differ, as long as it is consistent for a project that is good.

vivid halo
#

C# and Unity's official documentation prefer a certain style. The style wasn't chosen by dice roll.

heady iris
#

why not push all of the braces to the right side of your screen so you can pretend you're writing Python

#
    public void OhNo()                                              {
        if (true)                                                   {
            Debug.Log("Wow!");
            Debug.Log("This is great!");                            }}
vivid halo
#

Yeah guys, it's just preference

tawdry fox
leaden solstice
#

Yeah Python played smart and eliminated the possible arguments like this

vivid halo
#

Python introduced whitespace-dependent code which is terse but introduces its own issues.

heady iris
knotty sun