#archived-code-general

1 messages · Page 78 of 1

heady iris
#

I'm a little fuzzy on the nitty-gritty details of delegate types et al.

#

some languages (C# included, in unsafe contexts!) let you know exactly where a thing is in memory

#

that location is stored in a "pointer" (it points to something!)

muted sonnet
#

no point in getting into that rn tbh

scarlet viper
#

can I not put a MonoBehaviour on an obj, if the MonoBehaviour is inside a Package ?

muted sonnet
#

the main idea is, in C# functions can be put into variables

heady iris
#

it's very convenient for allowing flexible behavior

#

you can pass a function that compares things into a sort function

#

and bam, you can sort a list however you'd like

muted sonnet
#

yep

magic harness
#

If i set my raycast on one object and decide which object the pointer should interact with, its not going to stop interacting with the other objects because i have canvasses on Top of each other

heady iris
#

ah, so you have several unrelated canvases

magic harness
#

yeah

heady iris
#

perhaps you can have the first canvas say "didn't get anything" to the second canvas

#

which then tries its own raycast

mellow seal
#

private EnemyManager EnemyManager => EnemyManager.Instance;

is this same with assigning in awake or is it happening before awake

magic harness
#

I need to find a better way. But thanks for the help!

rustic ember
#

Very technical. I don't really think I understand to be honest. I got the help I needed though, so thanks

heady iris
#

actually, I guess I'd do it like this:

#

have a single input controller component

#

it is the only thing that listens to mouse input

#

it has a list of places to try that input in

#

it tries them in sequence until one of them says it did something

magic harness
#

The thing is that these other canvas have buttons that listen for the input independently

heady iris
#

It would be nice to have this Just Work without any explicit orchestration

#

but I dunno what to do about several canvases

muted sonnet
magic harness
heady iris
magic harness
#

I got a screen space object that is on top of my world space object

#

The screen object has buttons that i use to select what thing is going to move in my world space object, and the click on my world space object decides where its going to move

#

I basically need my screen space canvas to block my world space canvas. and im doing so by setting the blocking mask to the collision layer i set my screen space canvas

#

but somehow it isnt working

leaden ice
#

Aren't all of these problems solved automatically if you just use the event system callbacks for everything? E.g. IPointerClickHandler

scenic hinge
#

Sorry I think it’s actually called “Draw Order” for a canvas

magic harness
#

sorting layers? they are in place already

#

collision layers already

scenic hinge
#

“UI elements in the Canvas are drawn in the same order they appear in the Hierarchy. The first child is drawn first, the second child next, and so on. If two UI elements overlap, the later one will appear on top of the earlier one.”

thin aurora
magic harness
thin aurora
#

Not that it matters here

scenic hinge
magic harness
#

it is not a draw problem. Its a problem where my mouse click interacts with the multiple canvas where i only want it to interact with the object that is on top

mellow seal
# thin aurora You're not assigning anything. The property in this case points to `Enemy.Instan...
private EnemyManager _enemyManager => EnemyManager.Instance;

without that => EnemyManager.Instance _enemyManager will be null so we are assigning did i understand wrong

im making skeleton like this

public class EnemyManager : MonoBehaviour
{
    private static EnemyManager _instance;
    public static EnemyManager Instance
    {
        get { return _instance; }
        private set { _instance = value; }
    }

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            return;
        }
        Destroy(gameObject);
    }


scenic hinge
magic harness
#

i have to have them enabled at all times

scenic hinge
#

Then I think it’s a design issue

thin aurora
#

But the code you're sharing is the actual assignment of Instance. It should not be relevant to my message.

scenic hinge
magic harness
#

the canvas on the bottom is just an Image. The canvas on top has buttons. They both need to be visible all the time because the image is my map

#

Whenever i click on the map, it moves a certain object to that position

scenic hinge
magic harness
#

i cannot dude

scenic hinge
magic harness
#

one is screen space the other has to be world space

#

and have different sorting layers and all

scenic hinge
#

Okay okay, so one disappears when the other is visible?

#

Screenshots?

mellow seal
magic harness
thin aurora
#

A property does not hold a value, it gets it from something else

#

If you define a property without an explicit getter, it's retrieved from something called a backing field

#

You're defining it to fetch it from EnemyManager.Instance

#

So the thing with properties is that you're not setting it in Awake, which prevents race conditions, which in turn is bad

scenic hinge
mellow seal
#

oh i got it, thank you very much

scenic hinge
magic harness
#

They are both interactable. I want that whenever i click on a button it doesnt run the functionality that does whenever i just click on the map

#

i want my screen space UI objects to block the mouse click event from reaching my world space canvas

scenic hinge
#

I understand now

lethal plank
#

very bruh moment

scenic hinge
#

I think that is fairly easy, you just create a bool that gets set to true when you click on the screen space GUI, then you query for that every time on the world space GUI, or you check which UI your pointer selects first and ignore interactions thereafter

magic harness
#

the bool doesnt work because if i set it to true after i click the screen space object then the functionality will run on world space anyway

magic harness
#

Managed to make it work like this ```c
private bool IsPointerOverUIObject()
{
PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
pointerEventData.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointerEventData, results);
return results.Count > 0;
}

I run this whenever i get Input.GetMousebuttonDown
scenic hinge
#

If it’s on the screen GUI then you just want to disable the pointer events on the world level

magic harness
#

ill discuss with the team which design option would be better

#

Thanks the help tho!

static matrix
#

How can I make it such that A prefab has itself as a variable in a script, but when I instantiate it, it remains the one in the prefab and doesn't go to the instance?

scenic hinge
# magic harness Thanks the help tho!

I think you’ll be hard pressed to find a cleaner solution when layering GUI, it’s often a lot easier to just know where your pointer is at all times, rather than just on click.

scenic hinge
static matrix
#

I need to be able to refrence the prefab an isntance is an instance of

scenic hinge
leaden ice
static matrix
#

do I need a separate var for each thing Im instantiating where I need this????

leaden ice
#

Not if you just relegate this behavior to a dedicated component on the prefabs and put that component on everything

static matrix
#

well I mean the spawner

#

the spawner would need a different variable to assign to everything at runtime

static matrix
#

waiit hold on maybe

scenic hinge
#

someList.Add(Instantiate(somePrefab));

static matrix
#

because It doesn't change in the prefab, so I can reference the prefab to set the referecne to the prefab

#

ok

#

hold on

scenic hinge
#

Hatebin

cobalt elm
#

Been looking through the docs and I cannot find whatsoever how the input is connected to the eventsystem, other than a base input module which I have no idea how that actually connects to my controller. I've been having a bug where my eventsystem is not updating to any new input modules simply because i do not know how to update it. Is there any way in the new input system to manually connect a controller to an input system? Thanks

#

this is also in the 2019.3 docs but... im using 2020.3 and there is no base input module?

scenic hinge
cobalt elm
#

Controller

scenic hinge
# cobalt elm Controller

So if you are looking for just generic input, you can use the input package, however I’d recommend looking for SAMYAMS inputsystem guide

cobalt elm
#

in the docs ive found, there is a base input module but that turns into a legacy input module in 2020.3 (the version im using). Thus leaving me with no where to find how to event system finds the input device.

#

Ok so now im thinking its the playerInput.uiInputModule

#

nope not really related

#

NEVER MIND IM FUCKING STUPID There is a nice little dif between "Event System" and "UI INPUT MODULE"....

scenic hinge
late prism
#

I am working on a VR game and I want a menu to spawn in front of the player. I got the code to place a model (book) always in front of my face. Now I need to rotate it so it faces me, any idea how I would do this?

Vector3 playerPos = playerHead.transform.position;
Vector3 playerDirection = playerHead.transform.forward;
Quaternion playerRotation = playerHead.transform.rotation;

Vector3 spawnPos = playerPos + playerDirection * spawnDistance;
instantiatedModel = Instantiate(model, spawnPos, playerRotation);
#

Currently it is facing outwards

heady iris
#

you should use Quaternion.LookRotation

#

make the book look at the player

late prism
#

Okay, I'll try it ty

leaden ice
heady iris
#

Bingo!

#

You give it a direction and an up vector

#

(It defaults to world up)

leaden ice
#

Yeah - seemed like world up was fine here - but if needed you can use playerHead.transform.up

stuck forum
#

is there a way to make it so that the in keyword prohibits value assigning on classes?
works for other types like int and float, but not for classes sadly

heady iris
#

as in, setting the fields of a class?

stuck forum
#

yea

#

i just want to read not write

heady iris
#

yeah, that's a common surprise for any language with a "read only" modifier

#

it's really just no assignment

stuck forum
#

damn

leaden ice
#

classes are passed by reference already

#

What are you trying to do?

#

You could always make a read only interface which the class implements and pass the object in as that type instead of its naked type

stuck forum
#

just pass in some values into a scriptable object which will be used later

stuck forum
heady iris
#

there's the alternative option

#

put a big mean comment that says you'll beat them up if they modify the object

stuck forum
#

that could work 😂

heady iris
#

but yeah, if you read the feature specification

#

it mentions that in was added to allow for structs to be passed by reference, but without allowing mutation

stuck forum
#

yea i read that, hence why im asking for a workaround

apparently c++ has what i need, but i dont do c++ so rip

stuck forum
leaden ice
#

Since void SomeMethod(IReadonlyPolygon polygon) { takes the interface as the parameter, it can only access things that are defined in the interface, such as the get-only property

quick kindle
#

hey all, lmk if theres a better channel to post this in: does anyone know of a store asset that you can use to generate graphs of nodes, like this map? ive tried using mapmagic2 which i thought would be cool as i could also use it to create fancy looking terrain, but im not able to get the spline (connection) data between the nodes (provinces) to use for the game logic

clarify: im looking for something that will let me generate procedural versions like this map, not just this map what i could build manually

stuck forum
heady iris
#

like the Unity Splines package

#

Although, I'm not sure what I'd do to decide on the exact shapes of the curves

#

It seems random as to whether they bend up or down

#

You just want the visuals, right? You aren't looking for something to actually store a graph of vertices (kingdoms/settlements) and edges (paths between them)?

cerulean oak
#

how do I make a canvas element capture clicks, but not capture drags?
so, the if I click and drag, the element below captures the drag, if I click and release, it captures the click

quick kindle
# heady iris You just want the visuals, right? You aren't looking for something to actually s...

no, the opposite. whats important for gameplay is the settlements + connections between them (ie i just need to know that settlement X is connected to settlement Y, not the exact path that is used to connect them), i need those in gameobjects/components for the gameplay. the terrain is just eyecandy. and i can manually recreate that map, but im really looking for something that allows me to procedurally generate a large variety of maps

heady iris
#

so you need to figure out which settlements are neighbors?

quick kindle
#

hmmmm in a sense? its not just proximity, though, some settlements could be physically close to another but not have a connection

#

sorry ive been beating my head against mapmagic trying to get this result so im thinking in those terms

heady iris
#

so you need to semi-randomly connect settlements together (without crossing the lines)

quick kindle
#

yeah. mapmagic2 does that part pretty well, i can have it scatter the settlements then pathfind and it generates a bunch of nice splines that connect the settlements in a satisfactory way... but then there doesnt seem to be anything in mm2 that actually outputs the splines, it just seems to be built to use them to draw textures on the terrain object, and i havent found a way of using the mm2 output to determine settlementX connects to settlementY

heady iris
#

ahh, I gotcha

#

I would expect that to be possible..

#

Never heard of the package before.

quick kindle
#

its pretty neat, what you can do with procedural generation of terrain, and even putting objects on it, but the splines module looks... unfinished

heady iris
#

i am trying to find documentation

cerulean oak
#

I'll just dissable it

quick kindle
heady iris
#

uh oh 🫠

#

ah, so this is a whole node-editor thingamabob

quick kindle
#

yeye

#

playing around with it a couple years ago, i was actually able to get some quite interesting procedural terrain out of it, and changing the seed would generate entirely new maps at runtime, pretty cool

#

so that green scatter node is what scatters my provinces (which can be seen as little clusters of houses), and then it flows into that orange interlink node which generates a bunch of splines to connect those provinces, and then the latest thing ive been trying is the orange scatter node, which takes a list of splines and creates a list of locations which i then dump "PathPoints" on to (the orange dots you see in the scene)

#

but theres no way within mm2 that i have found to attach any other data to them. trying to think of a way to use them to generate logical X->Y connection information after the mm2 generation is done

#

and then got to that point and thought "dammit is there another asset that could do this easily" 🙂

#

30 years of software engineering and im lazy af, i dont want to write code, i want to ship games XD

#

i can increase the # of objects placed in the scatter node

leaden ice
# quick kindle but theres no way within mm2 that i have found to attach any other data to them....

but theres no way within mm2 that i have found to attach any other data to them. trying to think of a way to use them to generate logical X->Y connection information after the mm2 generation is done
I wouldn't try to do all that stuff inside MM itself

I would just use MM to generate the terrain and the provinces themselves (with Objects in MM as you have done there). I would then basically just take over with my own custom graph generation logic. Pretty much just check within a radius of each province to consider as "neighbor" provinces and then it's just standard graph logic from there

#

other than drawing the splines of course...

quick kindle
leaden ice
#

You get it... just not from MM

#

Use the Unity splines package or similar and draw the edges of the graph

quick kindle
#

hm

#

looking into unity splines, never used em before

#

can they be used to write onto the terrain?

leaden ice
#

As a crude first pass you can just draw them as straight lines with simple LineRenderers

leaden ice
#

theoretically you can do whatever you wish

#

there's no built in terrain drawing feature though

#

Is there a reason they need to actually be baked into the terrain?

#

rather than for example separate meshes laying on top

quick kindle
#

ah not neccessarily baked into terrain, but i would like a visual effect

#

mm2 just has all these super nice nodes for splines, like you can have it keep the splines to minimal elevations, so it naturally wraps around steep mountains and such

#

and a stamp node that flattens the ground around the spline so it looks natural

#

its just frustrating bc it seems like mm2 gets me 99% of the way there, and if i handroll my own pathfinding and generation, i'm having to write a bunch of stuff that mm2 does for me, just to get that last 1%

heady iris
#

it would be very convenient to re-use the same paths, for sure

leaden ice
#

MM2 has a splines thing

#

sorry if this has already been discussed

heady iris
#

that's what's being used

leaden ice
#

ok tjhought so but wasn't sure

heady iris
#

it sounds like the problem is extracting that data, so that the logical connections between settlements matches the physical connections that were generated

leaden ice
#

Did the mapmagic documentation website go down? I can't seem to find it

#

Perhaps a casualty of the war?

#

nevermind I see the gitlab link above

heady iris
#

ok i genuinely thought for a moment that there was some kind of Holy War over map generators

#

i need to go lie down

quick kindle
leaden ice
vague slate
#

How can I get angle of clock arrow if I know it's forward vector?

leaden ice
vague slate
#

oof

    public static float SignedAngle(Vector3 from, Vector3 to, Vector3 axis)
    {
      float num1 = Vector3.Angle(from, to);
      float num2 = (float) ((double) from.y * (double) to.z - (double) from.z * (double) to.y);
      float num3 = (float) ((double) from.z * (double) to.x - (double) from.x * (double) to.z);
      float num4 = (float) ((double) from.x * (double) to.y - (double) from.y * (double) to.x);
      float num5 = Mathf.Sign((float) ((double) axis.x * (double) num2 + (double) axis.y * (double) num3 + (double) axis.z * (double) num4));
      return num1 * num5;
    }
heady iris
#

what about it?

vague slate
#

rather ugly implementation

leaden ice
#

Good thing there's no reason to ever even think about what's going on in there

vague slate
#

eh, I have to copy it to assembly that is connected to Unity Engine 🥴

heady iris
#

i c

shell scarab
#

There’s a render distance setting, it won’t render if the z plane of the camera is farther than this from a side of the decal.

polar marten
leaden ice
#

I'm just giddy they finally have the package. You know how long I had to recommend the Seb Lague package?

heady iris
#

It’s been pretty nice to work with

swift falcon
#

....

#

What is a spline ? I tried googling it but i dont see how u could make a game out of it or how splines could help to make a game

leaden ice
leaden ice
scenic hinge
#

That is a phenomenal example!

#

I always think of turning the page of a book when I think of splines

heady iris
#

Splines are polynomials between points, basically

#

rather than just straight lines

#

there are many flavors of spline

leaden ice
#

I prefer raspberry

scenic hinge
#

Let’s be honest though, “Linear Interpolation” is the best combination of words of all time.

swift falcon
#

Oooh

scenic hinge
#

It just sounds cool

heady iris
#

Slerp time

swift falcon
#

I'm sorry I guess just didn't that's what it was

#

I do see the usefullness now tho

scenic hinge
#

I do love slerping 🍦

heady iris
#

some kinds of splines also have smoothness guarantees

#

not only do the lines connect, but they also don't abruptly change direction

stuck forum
#

slurp

scenic hinge
#

Scammed by png

#

I’m gunna have to learn splines at some point, but city builders gaming

heady iris
#

i have a vague idea for a game that would need to generate a city full of buildings

leaden ice
#

A game that generates buildings in a city?

heady iris
#

Yes. It's going to be the Dark Souls of cities.

swift falcon
#

Lmao

scenic hinge
#

Inb4 waveform collapse does it for you

heady iris
#

well, speaking of that, lol

#

I've implemented that already

#

but I want to be able to place buildings along curved roads and, generally, get away from a perfect grid system

scenic hinge
#

I love some waveform collapse, much less painful than A*

heady iris
#

I started working on WFC with a sort of flexible world grid, then my brain fell out

heady iris
latent fossil
#

what's up

heady iris
#

it was very exciting

#

i screwed up rotations so many times. it is apparently impossible for me to imagine two tiles being rotated

scenic hinge
#

I should probably move over, I’m starting to think default Unity might eventually struggle with my implementation over netcode

#

Not sure yet

swift falcon
#

Is ECS any good?

heady iris
#

it's decently well documented now!

#

i found it approachable (as approachable as it can be, at least)

#

the tutorial series on building a bunch of tanks that drive around and shoot balls was extremely informative

swift falcon
#

Do u have to know all of DOTS or can u just use ecs

polar marten
heady iris
#

"DOTS" is an umbrella for a bunch of stuff

swift falcon
#

Ik what it is Job system burst compiler and ecs

heady iris
#

the entity-component-system scheme is certainly the bulk of it

#

yeah, I already knew all about Jobs

#

i used them to run gradient ascent for an RTS game's AI, haha

swift falcon
#

Async programming scares me

heady iris
#

although those jobs were synchronous

#

I learned all about async jobs with the ECS

#

it's very cool

#

you get to open the timeline and see tons of tasks running at once

#

insane performance

swift falcon
#

Yeah cus ECS uses structs instead of classes right

heady iris
#

that's part of it, at least, yeah

#

a lot of stuff gets passed around by reference

#

it takes a lot of code

#

I think things are getting stable now? They completely changed how Transforms work at some point

swift falcon
#

I've seen some talks on it

heady iris
#

maybe i'll give it another go during a game jam or something

#

make a horde shooter with 50,000 enemies

swift falcon
#

Are these game jams ever recorded ?

heady iris
#

the last few I've done were run by my uni

#

there's one this weekend

#

i am sick, so I might try building a VR game at home

swift falcon
#

Where are they at ? I think there have been some in Austin Texas but ive never been able to attend

shell scarab
#

I'm gonna ask this again since it's way more active now:

Is there a way I can check if a urp decal projector is currently visible?

potent sleet
#

GeometryUtility.TestPlanesAABB @shell scarab

shell scarab
#

@potent sleet sorry, I should have specified better:
I need it to work with the render distance setting of the decal too.

quick kindle
potent sleet
#

float distance = Vector3.Distance(mainCamera.transform.position, decalProjector.transform.position);

if (distance <= decalProjector.fadeScale)
{ // do stuff}

shell scarab
#

can you point me in a direction of finding a point on a box from a direction vector then? Because the render distance is not from the transform of the decal, but rather from the sides of the decal's 'box' that intersects with geometry.

shell scarab
#

thanks!

static matrix
#

ok so, How can I have a NavAgent tied to multiple navsurfaces? because I'm having a bug where my chaser will stop chasing when I leave the surface it is on

static matrix
#

wdym

#

its procedural, they bake when they spawn

#

how do I connect them?

heady iris
#

I know you can do Off Mesh Links between two chunks of the same surface

#

do you have multiple Nav Mesh Surface components?

static matrix
#

yes

heady iris
#

not sure on that one

static matrix
#

I tried that and then stuff started moving through walls

#

any ideas?

potent sleet
#

you have to procedurally attach the surfaces if they have gaps

#

with offmeshlink

static matrix
#

hmm

#

what if I make the meshes bigger so they overlap

#

will the agent switch mesh

heady iris
#

it would make sense

heady iris
#

I've only ever done one big surface (since I've never had particularly huge levels)

static matrix
#

I would do one big, but procedural

#

so I cant

potent sleet
#

Yeah surface works the same with offlinks

#

they removed general bake in 2022

heady iris
#

cool, then yeah, you'll want off mesh links

potent sleet
#

2022+ now you need to place surfaces 😵‍💫

heady iris
#

i like the new AI Navigation stuff

#

I use NavMeshes for sound propagation as well as navigation

potent sleet
#

yeah it was long overdue

static matrix
#

this is basically the issue, the ball wont cross the blank zone

potent sleet
potent sleet
#

it's a gap..

heady iris
potent sleet
heady iris
#

ooh yeah, and you can animate them getting on and off the wall when they change surfaces

#

neat

static matrix
#

but I can't predict exactly where a crossing will be, because the walls are oriented randomly, so then they would be able to get through walls I think

heady iris
#

you could add off mesh links by checking that nothing's in the way

static matrix
#

well its not fully random, its a layout with a random 90 degree orientation

potent sleet
static matrix
#

on runtime?

potent sleet
#

are your best friend right now

static matrix
#

ok issue

#

the game is already barely above 35 fps

#

and that sounds very performace heavy

heady iris
#

well, you'd do this just once

static matrix
#

although a lot of the stress is from graphics

heady iris
#

If you have an idea of where the joint is gonna be, then I would sample a random point in that area

static matrix
potent sleet
heady iris
#

then find the nearest edges of the two surfaces and do a raycast between them

#

or maybe overlap a box in that area

#

if it's clear, make a link

static matrix
#

hmm

#

I could also try and condense the structures so there's some space where walls will never be and put it there

potent sleet
#

you can check distance as well

#

so gap is not too big

static matrix
#

any tips on saving graphics performance?

#

I'm at a state where it looks nice, and I've already changed a bunch of settings

#

runs at 30fps usally

dusk apex
#

Use the profiler

static matrix
#

yeah

#

it just is like "Camera.Render: 80%"

potent sleet
#

post processing?

cold parrot
static matrix
#

yeah, although the game looks like crap without post processing

dusk apex
#

Output as in the profiler

static matrix
#

ok I'll look deeper into the profiler

#

the offmesh links both broke the AI and made it zoom all over the place, and also it still didn't cross the gaps

static matrix
#

yeah

#

this is not correct id presume

#

I do take solace in the fact that my AI code was working perfectly, I just didn't set up the navmeshes right

potent sleet
static matrix
#

thats the chunk

#

empty, this is the prefab

potent sleet
#

how are you setting offmesh link tho

#

if you're using Auto generate offmeshlinks you're gonna have problems

static matrix
#

Oh

#

I just added this component and set the size to be a bit larger than the chunk size

potent sleet
#

nahh man u generate the map you gotta do it correctly via script

static matrix
#

presuming I get the script working correctly, the off-mesh link should look like this? (Lets say theres no walls there)

#

does this define a cross-mesh area

#

sorry im being so asky

potent sleet
#

the 2 bigger cubes gizmos are StartPos and EndPos

#

right now they would go through middle spot to cross

static matrix
#

ah

#

ok ill figure it out

heady iris
#

I was reminded of something just now -- fuzz testing. You just...hammer the system with inputs for a long time and see if anything goes wrong.

Has anyone ever automated that in Unity?

#

I've used it to find quite a few bugs in Blender :p

#

i'm thinking it would be a good way to shake out any bugs in my UI system, for example, by mashing tons of inputs and trying to discover any weird edge-cases

#

all you'd need to do is enter play mode, then simulate a ton of random inputs

sly nacelle
#

I’m trying to figure out how to make a enemy shoot a projectile in the directing the enemy is facing because it changes direction

leaden ice
unreal zinc
#

hey guys, running into a major issues here with Unity 2022.2.14f1, fresh install, installed the visual studio tools, but when opening the C# unity project in visual studio it says the project type is not supported. This set up is on my laptop which is only different from my desktop PC in that the laptop has Visual Studio 2022 professional, and my desktop PC has the 2022 Community edition of VS

#

I've tried all the common fixes like reinstalling, running a 'repair' of visual studio, etc. still have the same problem

dapper hinge
#

Anyone know what I'm doing wrong?
I just have this

public class Keyboard : MonoBehaviour
{
    private TouchScreenKeyboard keyboard;
    public void OpenKeyboard() 
    {
       keyboard = TouchScreenKeyboard.Open("", TouchScreenKeyboardType.NumberPad);
    }
}

The OpenKeyboard() method get's called in the OnSelect event of an inputfield like in the image

#

No keyboard opens up though, I'm using Unity Remote 5 to test it

potent sleet
#

did you read the docs?

dapper hinge
#

yes, I'm a little confused with their examples though

#

Not sure what all of these GUI.button() if statememts are about

potent sleet
dapper hinge
#

I know, I'm testing this on my Samsung Phone with Unity Remote 5 App

potent sleet
#

Unity remote is just streaming your editor

#

is not a native mobile app

dapper hinge
#

Oh

#

so the only way to test if this works is to build the app and get in onto my phone?

potent sleet
#

make the APK

dapper hinge
#

already on it 👍

cerulean oak
#

how do I check if a rect transform has the mouse position?

#

I tried RectTransformUtility.RectangleContainsScreenPoint(rectTransform, Input.mousePosition)

#

also tried RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, Input.mousePosition, null, out _)

#

tried using Camera.Main

#

tried doing rectTransform.InverseTransformPoint (gives some huge numbers)

#

nvm got it

dapper hinge
#

Camera.main.ScreenToWorldPoint(Input.mousePosition); Get's you the coords of the mouse
rectTransform.TransformPoint(rectTransform.rect.center);Get's you the transforms coords too I think

#

oh

#

:/

heady iris
#

TransformPoint goes from local space to world space

#

InverseTransformPoint goes from world space to local space

shell scarab
#

@potent sleet I need some more help here if you can. Or anyone really.

I don't really know why this decal is appearing before the draw distance. I have this, which adds the distance (from the center of the bound (drawn in blue) to the edge of itself) to the render distance. I then check the distance from the camera's near clip plane (just camera's forward multiplied by the near clip plane distance in world space) to the center of the bound. Yet it's still slightly off, I don't know why.

Vector3 zPlanePos = Camera.main.transform.TransformPoint(Camera.main.transform.forward * Camera.main.nearClipPlane);

_bounds.IntersectRay(new Ray(_bounds.center, (zPlanePos - _bounds.center).normalized), out float distance);
float realDistance = (-1 * distance) + projector.drawDistance;

Debug.Log(realDistance);
Debug.Log(Vector3.Distance(zPlanePos, _bounds.center));

Yet the decal appears before the second debug log statement is equal to the realDistance.

#

(in the image I'm logging Vector3.Distance(zPlanePos, _bounds.center) > realDistance). It's true, yet the decal is shown. Also I am using the near clip plane of the camera instead of the player position because I could not figure out why the decal was appearing before the player got close. Using the near clip plane position makes it almost correct. almost.

heady iris
#

does the behavior change if you change the near clip plane?

#

if not, then that's probably not relevant

shell scarab
#

still can't figure out why it renders before the distance of the box from the center of the box + the render distance

heady iris
#

also, I'm thinking of restructuring my entire game, again, and I could use a sanity check

Right now, each stat in my game -- health, stamina, mana, whatever -- is identified by an enum. This has already led to headaches, as seen in exhibit A:

#

I had the idea to make a ScriptableObject type that represents a stat. The type would hold localized strings for the name/description of the stat, plus the stat icon.

#

one issue I see that is that I'll need to do something like Resources.LoadAll to get a list of every stat

#

instead of just iterating over the values of the Stat enum

#

(i'll also be adding more kinds of stats, some of which are conceptually different from others. it'll be about as elaborate as Elden Ring/Nioh/etc.'s list of stats)

#

so those will probably need different types

#

I guess I should just give it a whirl and see how it feels. I'm still very early in development.

sly nacelle
#

I have this script but when it runs the projectile does move.

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

heady iris
#

please use a paste site

shell scarab
heady iris
#

swinging the sword costs 10 stamina, and deals 20 vitality + 10 stamina damage

#

so, in this case, I'd just be replacing the enum dropdown with a field that holds a Stat reference

#

One place that this seems like a win is localization: I'm doing some...suspicious stuff right now

#
    private string StatKey
    {
        get
        {
            return System.Enum.GetName(typeof(Stat), stat);
        }
    }
#

this gets turned into a LocalizedString

#

actually, basically everything I do with enums feels suspicious

#

enums are funky little guys

shell scarab
#

tbh I like enums bc you can use it as a flag enum and use bitwise operators so you can easily say "this stat or this stat or this stat or this stat or this stat" in an if statement. I would even set up a method that I could use to take points away from multiple stats based on an int that represents the flag enum.

heady iris
#

yeah, although I don't have it set up properly for that

#

since the enum values are just sequential

#

I am using enum flags like that in another place, where different interface elements are enabled depending on the current game state

#

I think the big hang-up is iterating over all of the stats

#

I guess I'd just make a static class that does a big Resources.LoadAll once

shell scarab
#

why do you need to iterate over all the stats with the current system?

heady iris
heady iris
#

it'd even sort them correctly so they show up in the order I want

#

rather than just "whatever order they have in the enum"

shell scarab
#

Well, are you concerned with performance or ease of use? bc you said you're in early development, so it's not a good idea to be concerned with performance right now, or so I've heard.

heady iris
#

Ease of use generally wins.

#

Critically, it shouldn't feel gross to add and remove stats later

heady iris
#

I am thinking about the potential cost, though

#

the big thing will be that I will look up stats with a SO reference, rather than an enum value

tawdry tulip
#

Hi, I'm facing a problem with my game, everything was going smoothly and all of a sudden i can't see the map, even by restarting the game
The maps shows up again when scaling the camera by 30*

shell scarab
heady iris
#

ya

#

I think I'll give it a go

#

time to create like 300 errors

shell scarab
#

lol

heady iris
#

hey, deleting the Stat enum only made 9 errors

#

that's concerning

#

🤨

shell scarab
#

maybe you should make a static class and have that handle everything, so if you decide to switch back to enums later you only need to change it in one place rather than a bunch of places @heady iris

heady iris
#

Yeah, I'm definitely gonna have a static class that holds all of these SOs

#

thanks!

shell scarab
#

yup! And that way if you want enums it shouldn't be.. too hard.. hopefully.. to switch back.

heady iris
#

knock on wood

#

and the compiler

heady iris
#

I'd fiddle with more variables

#

I wonder if it's accounting for how the box could be rotated

#

so that a corner is facing you

#

you'd need to add...a factor of sqrt(3)?

shell scarab
#

the render distance is definitely from the edge of the box to the camera. So if you stood in a spot and rotated the decal so a corner was within range, it would start rendering.

heady iris
#

ah, okay

shell scarab
#

i give up on that tbh. I'm just gonna add a radius and manually control the fade and tell my team 2 bad lol

#

(they wanted it to work with the fade value on the projector)

heady iris
#

I've had weird problems with decals, but not that one, at least :p

shell scarab
brittle sun
#

Anyone have any suggestion in dealing with navmesh agent
isOnNavMesh returns true but
isStopped us causing error
can only be called on an active agent that has been placed on a NavMesh.

heady iris
# heady iris I think I'll give it a go

ah, one nuisance: this is going to work great for stuff like weapon scaling, since the weapon can have a list of stats that are used to determine its damage

...but it's inconvenient for things like health. An entity checks every update if it's at 0 health, and, if so, dies. But now it doesn't really know what "health" is.

#

It just has a bunch of stats.

#

stuff like "health" and "stamina" feel very different from things like "strength" and "reflexes"

#

they're numbers that go up and down all the time and have very concrete meanings

#

I guess I can just tell the entity what stat should be used for deciding if it's dead, etc.

#

that could certainly lead to interesting things like an enemy that only dies when it runs out of mana

hexed oak
#

Having an issue with Unity sort order--it seems that the sort order doesn't take effect unless I modify it after hitting play

#

I have a canvas at sort order 0, then a background sprite at 1, and text at 2. But at runtime the background sprite renders over the text. If I change the text sort order to 3 at runtime (or background to 0) then it works. But it has the same issue every time I rerun it

mellow seal
#

What is the best way to surround enemys around player

I have found one tutorial about that which has this script

    private void MakeAgentsCircleTarget()
    {
        for (int i = 0; i < Units.Count; i++)
        {
            Units[i].MoveTo(new Vector3(
                Target.position.x + RadiusAroundTarget * Mathf.Cos(2 * Mathf.PI * i / Units.Count),
                Target.position.y,
                Target.position.z + RadiusAroundTarget * Mathf.Sin(2 * Mathf.PI * i / Units.Count)
                ));
        }
    }

But problem in this if target is not accesable (out of navmesh area) enemys will go nuts.

or i can create waypoints around player and every enemy will check the closest and then move to that but this time there will be a lot of distance check which will bad for performance

can you suggest me bast way to achieve that

sacred dove
#

Hi! I have a need to send some web requests to initialise objects. I want to do it in a coroutine, but I need them to be executed in the order they are added, otherwise everything will break. Currently I have this:
There is ICoroutineTask interface with methods Start, Wait and Finish.
There is WebRequests class that generates ICoroutineTasks from a UnityWebRequest, with Start Wait and Finish with Wait being request.SendWebRequest().
The setting of local variables is done in Finish method
And finally the code for resolving the enqueued tasks is:

        private IEnumerator WorkCoroutine()
        {
            while(_running)
            {
                if(_tasks.Count == 0)
                {
                    yield return new WaitForSeconds(0.1f);
                    continue;
                }
                var task = _tasks.Dequeue();
                Debug.Log("Dequeued task");
                task.Start();
                yield return task.DoWork();
                task.Finish();
                Debug.Log("Finished task");
            }
        }

But what I do does not work..

What is the correct way to do something like that?

simple egret
tulip quartz
#

Hey, Im very confused as to why putting the yield return null specifcaly there makes this last 0.6 seconds. Why does putting it at the end of the function for example make it transition instantly? Doesn't yield return null basically not do anything? Or at least thats what I though

#
    IEnumerator solveFade()
    {
        float delta = 0;
        float duration = 0.6f;
        Color start = bgMesh.material.color;
        while (delta < duration)
        {
            delta += Time.deltaTime;
            yield return null;
            bgMesh.material.color = Color.Lerp(start, "246F2A".Color(), delta / duration);
        }
        Module.HandlePass();
        
    }
late lion
mellow seal
tawdry tulip
#

Hi, I'm facing a problem with my game, everything was going smoothly and all of a sudden i can't see the map, even by restarting the game
The maps shows up again when scaling the camera by 30*, i tried changing the Z axis but it dont do anything

lusty seal
#

can some one help me I'm trying to create Jenga as an asset but as soon as i start the project the blocks fall is there a better way to do this i'm using physics in this example but the blocks slide all around not sure what to do can i get soeme hlep please

heady iris
#

i don't think you're going to be able to create a game of jenga with unity physics

#

maybe if you crank the bounciness down and the friction up?

#

i dunno what constraints VRChat puts on you

lusty seal
#

i created a physic material and took off bounciness i might need to crank the friction up maybe that works

lusty seal
#

just needed friction

waxen burrow
#

Hello, Im working on a new movement system based off a tutorial. The system works fine but there are a few tweaks that need to be made, one of which is giving me a bit of trouble. When jumping (with current system) despite having no "air control" the players rotation is still able to change the direction of the in air velocity. I want to make it so that when in the air you are still able to look around but do so wont change your momentum.
Heres le code: https://hastebin.com/share/ididitupit.csharp
I should note that I've done a few tests without much success like the if statement at line 134, feel free to pretend that isn't there

cerulean oak
#

my mind is gonna blow up

#

I had a property, with a getter and a setter. In the setter, I set the value of a privatefield, and I printed "Field set"

#

the private field was not accessed anywhere, only the getter and setter

#

and, for some weird ass reason, the private non serializable field is initialized to a default value

#

and it is a struct, not an object

#

without the setter being called

#

what in the world can be going on?

#

if the field was public, I get it can be assigned, because its a MonoBehaviour, but with a private field? it should be null

mortal thistle
#

Hello, is there a way to create a assetbundle without using Unity ? For my app, I need to get a list of asset from a server, so I'd like a script that fetch files from a list, make an assetbundle with them, and return the result. I got some result using python but the result assetbundle is compressed, so when using UnityWebRequestAssetBundle.GetAssetBundle(), I get :
Error while downloading Asset Bundle: Failed to decompress data for the AssetBundle
Is there a simple way I'm missing here ?

cerulean oak
#

does unity not allow any fields in a MonoBehaviour to be null?

heady iris
#

you can have plenty of null fields

#

but

#

structs cannot be null

#

(barring using Nullable stuff)

#

it's like trying to have a null float, or a null int

leaden ice
heady iris
#

it is a value type, not a reference type

leaden ice
#

If they're not serialized they'll be null

cerulean oak
#

its an object

#

not a struct

leaden ice
#

structs are objects

#

they're not classes though

cerulean oak
#

meant a class yeah

simple egret
#

If it was serialized in the past it might still set a value. Try changing the field name, just to be sure

heady iris
#

okay, so it is a class

heady iris
#

this is a non-serialized field

cerulean oak
#

^

leaden ice
#

Oh sorry I butted in late here

cerulean oak
#

its private, and I didnt specify for it to be serialized

#

also this behaviour stops happening and comes back again basically randomly

#

wich is even more weird

leaden ice
#

Shouldn't happen, but if you have an example feel free to show evidence

heady iris
cerulean oak
#

I ended up making a giantic botch, and setting a boolean to true when the variable is assigned using the property. The property only returns the object if that boolean is true, otherwise it returns null

leaden ice
#

It's not a static field is it?

cerulean oak
#

no, not static, but its a singleton

#

so im assigning the MonoBehaviour to a static field

leaden ice
#

Can you show the code etc

cerulean oak
#

its somewhat big and I cant seem to reproduce it standalone

#

because it happens randomly

leaden ice
#

I'd guess that something else in your code is causing it then

#

And it's obfuscated by the complexity of the code

cerulean oak
#

but its a private field, and nothing changes it other than the property

#

and im not using reflection or anything like it

heady iris
#

do you have any of this stuff set

#

well, unset, more importantly

#

i wonder if this is somehow tied to something not getting cleared when entering play mode

#

since you did say it's a singleton

cerulean oak
#

I haven't touched them, but where are they?

heady iris
#

Project Settings > Editor

#

They let you skip some steps while entering play mode (very nice for rapid iteration)

#

with the caveat that skipping the domain reload can cause some Funny Stuff

cerulean oak
#

all unset

heady iris
#

okay, so that's not it

heady iris
#

for a sanity check, do you find any extra references if you shift+F12 the private field?

cerulean oak
#

ctrl + F?

heady iris
#

no, shift+F12 to find all references

#

(i think that's the shortcut in VS)

#

it finds every place in your code that references something

#

the opposite of F12, which takes you to where something is defined

cerulean oak
#

ctrl + shift + F in rider

heady iris
#

ahh, rider, gotcha

cerulean oak
#

and nope, no references

#

even if I comment it out, the only lines that have an error are the property lines

stark turtle
#

could someone help me find out why this function isn't working properly? The debug.logs show non negative values correlating with the input, but the object this is attatched to doesn't change at all (iskinematic is off)

private void ApplyMovement()
    {
        Vector2 drift = new Vector2(movement.x, movement.y);
        Vector3 velChange;

        // Apply the drift and clamp the player's velocity to the maximum speed
        Vector2 rbVelocity2d = new Vector2(rb.velocity.x, rb.velocity.y);
        rbVelocity2d += drift * driftSpeed; //* Time.fixedDeltaTime;
        rbVelocity2d = Vector2.ClampMagnitude(rbVelocity2d, maxSpeed);

        // Apply drag to slow down the player's movement
        //rbVelocity2d *= Mathf.Pow(1 - drag, Time.fixedDeltaTime);
        //zVelocityChange *= Mathf.Pow(1 - drag, Time.fixedDeltaTime
        //rb.velocity = new Vector3(rbVelocity2d.x, rbVelocity2d.y, zVelocityChange);
        velChange = new Vector3(rbVelocity2d.x, rbVelocity2d.y, zVelocityChange);
        velChange *= speed;
        rb.AddForce(velChange, ForceMode.VelocityChange);
        Debug.Log("rbvelocity: " + rbVelocity2d);
        Debug.Log("rb . velocity: " + rb.velocity);
        Debug.Log("drift: " + drift);
        Debug.Log(movement);
    }```
inner yarrow
#

In the editor, there's this nice system for moving an object based on its center, which takes its childrens' position and scales into account. Is there any built-in way to do this through code, or should I make my own function for it?

cold parrot
cerulean oak
cold parrot
#

no, world position

inner yarrow
# cerulean oak you mean moving localPosition?

In this case I want the local position because I'm using a script that creates a bunch of 3d text objects, but they are centered at the bottom left, so I want to set their local position to make them centered around the parent object.

cerulean oak
#

so yeah then do what anikki said

inner yarrow
#

alright thx

cerulean oak
#

get the mean position, calculate the shift, then apply the shift to the localpos

somber ether
#
PlayerPrefs Sets "Variable" + ProductNumber | 1
// Player now owns Variable4 & Variable7

Array Products [10]
Instantiate All PlayerPrefs Variable_ that are 1
```What would the code be to do such thing that instantiates shop products that playerprefs only equal 1 to, using the count of how many are in the array from inspector you defy where the loop check ends??
cerulean oak
#

idk if im having an ictus or that made no sense

somber ether
cerulean oak
#

I mean the sentence

#

I dont get what you mean

somber ether
#

If you have a shop in a game for buying avatars and someone buys something, you dont want them to buy it again

#

So I want to only instantiate playerprefs that they own (for the tab where they can equip their purchased ones)

cerulean oak
#

you can use
PlayerPrefs.SetInt("item" + itemIndex , 1);
to store the purchased items
and
```PlayerPrefs.GetInt("item" + itemIndex) == 1````
to get if an item has been purchased or not

somber ether
#

No, because when theres 50 items in the shop we dont want to check each individual pref

cerulean oak
#

so dont use playerprefs

somber ether
#

regardless of save method youll need a loop

cerulean oak
#

you could also use the int as a flag, and store 32 bools per int

#

but like

#

just

#

dont use playerprefs

somber ether
#

why not

cerulean oak
#

idk

#

you are the one who doesnt want to call one GetInt for each item

#

why not?

somber ether
#

because thats weak code, using else if that many times

cerulean oak
#

what?

somber ether
#

youd rather just use a foreach loop to check the array for all the items you do own and instantiate those into the shop

cerulean oak
#

just use a loop

somber ether
#

I know to use a loop, thats not the question I asked. I am asking someone who is smart enough to give a detailed code

#

Thats what I have so far

#

Which is likely wrong

cerulean oak
#

that wont work

#

productArray.Count is always the same

#

you need to use a normal for loop

potent sleet
cerulean oak
#
for (int i=0; i<productArray.Count; i++){
    var product = productArray[i]
    if (PlayerPrefs.GetInt("item" + i) == 1)
        //whatever
}```
somber ether
# potent sleet what are u trying to do ?

inspector has 50 product prefabs, the shop instantiates all of them that you have not purchased yet, the ones you have not purchased are playerprefs 0. How do you instantiate a prefab like that

potent sleet
#

why not Dictionary

somber ether
#

I have one tab where ppl equip owned items, and one tab where ppl buy new items

#

so on start I generate the playerprefs to the size of the array. Now for next loading when it will instantiate all the products that are 0(not bought yet)

potent sleet
#

oh

#

array of gameobejct

#

array doesnt have count

#

it has length

#

cause its fixed

somber ether
#

I added the ], sorry. But thats the code so far

#

So it should instantiate all the purchased prefabs only

#

such as producttype9

solemn raven
#

hi,
i have a drag and drop situation , where i want to get the item the mouse pointer is hovering on once drag ends to make a drop

    public void OnEndDrag(PointerEventData data)
    {
        GameObject go = data.pointerDrag;
        if(go)Debug.Log($"go:{go}");
    }

the value of go is always the original parent before drag , not sure why

latent latch
#

Best to debug with all the other drag events at once

#

and onpointerclick

solemn raven
#

i also did that

public void OnDrag(PointerEventData data)
    {
        Debug.Log($"Draging :{data.pointerDrag}");
    }

also the original parent even though iam hovering over many other objects

#

is there is a way to just get the object underneath the pointer at anytime regardless of the drag event ? cause it seems to be buggy

latent latch
#

Could be like a raycast problem perhaps? Is there something blocking what you're trying to drag? For detecting what's underneath the pointer when dragging, I would assume you could just cast a ray yourself assuming you've not repositioning what you're dragging (and is under the pointer blocking the ray)

solemn raven
#

thanks , i will try that 🙂

potent sleet
latent latch
#

I havent really used it for a while, I just remember a lot of the drag events being fluff. You only needed like the OnEndDrag for it all to work. (still, the other events are needed to display you 'moving' the ui element for the user)

somber ether
#

My debug log says its going to spawn 3 different types of prefabs, but it only spawns prefab #2 three times, whys that?

potent sleet
#

I would not use rely on playerprefs for this..

somber ether
potent sleet
#

just cause it's working doesn't mean it's not flimsy code but I guess

somber ether
#

Im not staying with playerprefs, its just the fastest way for now so I dont need to write obsessive classes for file saves

potent sleet
#

so you know the value ur actually getting

#

not everything needs to be 1 liners

#

var productIndex = PlayerPrefs.GetInt("producttype" + i); Debug.Log(productIndex )

somber ether
#

Ah I see what went wrong. im getting the value of the prefs

#

The value is always going to come out as 1

potent sleet
#

is product type supposed to be a bool

somber ether
#

When you buy something from the shop it takes the product ID and sets its int to 1 as you now own it.

#

Now I need to instantiate all of those that exist/purchased

#

So the player can equip it

#

I can solve it tho

#

Instead of setting each product to 1, set the product to the product id

potent sleet
#

what's wrong with

public class Product
{
    public int Id;
    public string Name;
    public string Description;
    public GameObject ProductGO;
    public Product(int id, string name, string description, GameObject go)
    {
        this.Id = id;
        this.Name = name;
        this.Description = description;
        this.ProductGO = go;
    }
}```
#

then you on purchase store them in your player inv..

#

List<Product> for example or Dict

somber ether
inner yarrow
#

When building a mesh through code (i.e. creating a vertice array and a triagle array), how would I specify which colour should be used for each triangle?

spare dove
#

Im fudging around with a save system, and Im wondering if there is a nicer way to give many instances of a prefab a unique key to save wether they have been collected or not? Right now im just randomly typing a string in

spare dove
potent sleet
# spare dove Elaborate?

You mean when you save with the items you collected you don't want to reload scene and find the stuff you picked up right ?

spare dove
#

exactly

potent sleet
#

yes make each object have a unique Id with GUID

#

incorporate that On Loading /Saving

spare dove
#

How would that differ from manually typing in a string?

potent sleet
#

yeah it's faster and more efficient

spare dove
#

ah

#

allrighty, ill do that then, thanks 😄

potent sleet
#

but with GUID

#
  public string ID => _id;

        private void Awake()
        {

            idDatabase ??= new SerializableDictionary<string, GameObject>();

            if (idDatabase.ContainsKey(_id)) Generate();
            else idDatabase.Add(_id, this.gameObject);
        }
``` for example
spare dove
#

yeah i got it working 😄

#

the only thing is, if there is a way to make this happen when i drop something into the scene, so i dont have to remember to go use it on every object

#

[ContextMenu("Generate ID")]
private void GenerateGuid()
{
id = System.Guid.NewGuid().ToString();
}

potent sleet
#

if not generate

#

I store mine in a DB

#

so I check the Dict

spare dove
#

ill try it, otherwise ill just make it crash the game if it hasnt got an ID so i cant miss any :p

#

yeah I have a serializable dictionary i put all the "flags" in, but I so far I only had big stuff, not large amounts of pickups

sly nacelle
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

potent sleet
potent sleet
zenith iron
#

how do I retrieve data from an sqlite database and output it into a text object?

potent sleet
zenith iron
#

this is what i have so far, this class creates all the methods for my database, what i want to be able to do is call a method from another class to retrieve for example the first name of a student with a certain id number

potent sleet
#
    [SerializeField] private TextMeshProUGUI itemText;

    public void SetItemText(string text)
    {
        itemText.SetText(text);
    }
}```
potent sleet
#

so you can retrieve it whenever

zenith iron
potent sleet
#

unless you update the data often

#

otherwise you could put it into a method ofc

#

on my example I map my object like so

public class Item
{
    public string Name { get; set; }
    public int Damage { get; set; }
}```
List<Item> items = new List<Item>();

```cs
  while (reader.Read())
    {
        Item item = new Item();
        item.Name = (string)reader["name"];
        item.Damage = (int)reader["damage"];
        items.Add(item);
    }

    reader.Close();```
pure vapor
zenith iron
fervent plover
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

plucky karma
#

Really should implement your own constructor with expected parameters value.

zenith iron
#

@potent sleet, i didn't fully understand your examples but after googling i came to this method to call information from the database, however this error keeps popping up from the first screenshot which when double clicked into sends mi the this specific line in my code in the second screenshot

dull yarrow
#

I have a object with a script "Game Manager"
And i instatiate a object that on start gets that script from Game Manager:

   floor_Teams_Data = gameManager.GetComponent<Floor_Teams_Data>(); ``` 

and another action uses some function of that floor_Teams_Data reference and i get an error that "Object reference not set to an instance of an object"
I look at the inspector and the reference is there

What steps can i do to debug this? I lost almost 30 min trying to find a solution
timid meteor
#

Is there a way to slow down time only inside a capsule collider? This is what I have atm

#

I use this to generate the shape but I don't know what to do next

plucky karma
#

I think I understand what you want to achieve, but it requires handling your own physics setup. You'd need to handle all of your object velocity to be able to control "time" when inside a trigger volume.

timid meteor
#

ah ok

#

I used the script about to assign a gravity modifier only to that area and it works so far

#

and I was wondering if I could do the same.

timid meteor
#

hit.transform.gameObject.GetComponent<Rigidbody>().AddForce(new Vector3(0, -30, 0), ForceMode.Acceleration);

#

anything that hits that generated capsule gains a gravity modifer

#

could I just swap it and do

#

Time.timeScale = scale;
Time.fixedDeltaTime = scale *.02f;

#

?

#

something like this kinda?

timid meteor
#

hit.transform.gameObject.GetComponent<Rigidbody>().Time.fixedDeltaTime = 0.02f *?

potent sleet
#
 private void DisplayWeapons()
    {
        using (var connection = new SqliteConnection(dbName))
        {
            connection.Open();

            using (var command = connection.CreateCommand())
            {
                command.CommandText = $"SELECT * FROM {WeaponsDB};";

                using(IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                      //etc..``` 
@zenith iron
potent sleet
plucky karma
timid meteor
#

ah

#

would you know any forms or videos I could follow to learn how to do that?

blazing smelt
#

My object has an instance each of Script A and Script B.
During Awake(), Script A references a UnityEvent in Script B, and adds a listener to it to run a function in Script A.

Awake() in script A runs properly, and so does the UnityEvent in Script B, but the listener is not running. I think it's not being added in the first place (possibly due to the event somehow being triggered before Awake() runs), but I don't know hot to check this.

All of UnityEvent's built-in functions only work for its persistent listeners, so I can't use those.

Thoughts?

blazing smelt
analog echo
#
public void ContarCantNoticias()
    {
        dbReference.Child("noticias").GetValueAsync().ContinueWith(task =>
        {
            if (task.IsFaulted)
            {
                Debug.Log("TASK FALUTED xD");
            }
            if (task.IsCompleted)
            {
                dbReference.Child("noticias").RunTransaction(mutableData =>
                {
                    IDictionary<string, object> cantNoticias = (IDictionary<string, object>)mutableData.Value;
                    Debug.Log(cantNoticias.Count);
                    debug.text = cantNoticias.Count.ToString();
                    mutableData = null;
                    return TransactionResult.Success(mutableData);
                });
            }
        });
    }

When I add this 2 lines of code it works on the 2nd time I call the void (I dont want this to happend):

  Debug.Log(cantNoticias.ToString());
  Debug.Log(dbReference.Child("noticias"));

But if I remove them it just stops working (also dont want this to happend tho)

blazing smelt
#

@cosmic rain okay putting it in Start() works

inner yarrow
#

When building a mesh through code (i.e. creating a vertice array and a triagle array), how would I specify which colour should be used for each triangle?

cosmic rain
cosmic rain
analog echo
zenith iron
swift falcon
#

can i pay someone to teach me coding?

potent sleet
zenith iron
#

@potent sleet what version of unity are you using?

swift falcon
#

fuck

potent sleet
#

2021

zenith iron
#

erm, i assume so

potent sleet
zenith iron
#

no, this is first time trying it, just trying to locate the dll files

potent sleet
#

it should be in your Unity installed folder

zenith iron
#

yeah from the version i am currently using, i will delete it and try again just to be sure i put the correct one in

potent sleet
zenith iron
#

2021.3.22f1

#

no, it's in the normal unity folder

potent sleet
#

then it might be the wrong one

zenith iron
#

you think the dll file in the 'unity' folder is the wrong one?

potent sleet
#

yes it should be unityjit

#

which is for Just in Time

#

compiling

zenith iron
#

i'll give it a go

potent sleet
#

Mono dll from unityjit-win32

#

but then you can just dl the sqlite x64 version

zenith iron
#

what do you mean?

potent sleet
#

did you not download the SQLite precompiled binaries ?

zenith iron
#

oh you mean download the x32 version of it?

potent sleet
#

nah x64 should be fine

zenith iron
#

oh yeah that's the one i originally downloaded

plucky karma
#

Has anyone run into this weird issue where I'm trying to write/compile a shader, this message pop up from a different file?

#

What does it means??

cosmic rain
#

When unity compiles shaders it expands the macro's in other files. Are you using any unity macros in your shader?

plucky karma
#

I think that was it... I was using UnityCG.cginc

Nope...

zenith iron
#

@potent sleet not sure jif was the correct version, now giving me a different error

#

gonna attempt to run the code on my mac see if that does anything different

potent sleet
#

here's my dll

zenith iron
#

can you use nosql in unity?

potent sleet
#

there is also google's Firestore. or w/e is called

zenith iron
#

you had any experience with firebase?

#

firestore?

potent sleet
#

I never use it, I'm a mongodb fan so I stick to that

zenith iron
#

is it easy to use with unity?

potent sleet
#

with Realm it is

#

it has unity sdk

zenith iron
#

might have to give it a go, this sqlite is fucking me off

potent sleet
#

it's much easier to work with a Object based db

#

depends on your usecase ofc

#

fuck writing sql code

zenith iron
#

lol yep, i only chose to use it because i'd done it before

potent sleet
#

def give Realm a try if you have no problem working with POCO

plucky karma
#

I still like writing SQL code tho...

potent sleet
#

PHP flashbacks

plucky karma
#

back at my old job, I wrote 200 lines of SQL code, it was primarily used to generate material resource planning.

#

Several temp table was created to hold information and output tons of planning. Which was kinda cool to learn.

zenith iron
#

idk what POCO is tbh

potent sleet
plucky karma
#

Plain Old C Object 😄

potent sleet
#

Plain Old CLR Object

#

POJO xD

shell scarab
#

I'm getting this error:

RenderTexture.Create failed: colorFormat & depthStencilFormat cannot both be none.

when I call this:

Camera.main.Render();

but the render texture is set to this:

RenderTexture rt = new(Screen.width, Screen.height, UnityEngine.Experimental.Rendering.GraphicsFormat.R32G32B32A32_SFloat, UnityEngine.Experimental.Rendering.GraphicsFormat.None);

or this (tried both):

rt = new(Screen.width, Screen.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);

But neither of those have both colorFormat & depthStencilFormat set to none, so I'm very confused. Any help with this?

dusk apex
shell scarab
dusk apex
#

4th parameter

shell scarab
#

this is the constructor I'm using:

#

it says color format is the 3rd

dusk apex
shell scarab
#

even then, they both aren't none

dusk apex
#

The 4th was explicitly set to none by you.

#

UnityEngine.Experimental.Rendering.GraphicsFormat.None

shell scarab
#

like I said, I'm using the constructor where the 3rd parameter is the color format.

shell scarab
dusk apex
#

Look at the docs...

#

There are only three overloads and only one taking more than one argument.

shell scarab
#

some are excluded because it's the same thing but without some 'optional' variables.

shell scarab
dusk apex
#

Well I'm not sure then.

shell scarab
#

I'll try using the one in the docs but

dusk apex
#

Error is never wrong so 🤷‍♂️

quartz folio
#

What's the stacktrace from

shell scarab
# quartz folio What's the stacktrace from

this is the full thing:

RenderTexture.Create failed: colorFormat & depthStencilFormat cannot both be none.
UnityEngine.Rendering.RenderPipelineManager:DoRenderLoop_Internal (UnityEngine.Rendering.RenderPipelineAsset,intptr,System.Collections.Generic.List`1<UnityEngine.Camera/RenderRequest>,Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle)
CharacterMovement:GenHitParticles (UnityEngine.Vector3,UnityEngine.Renderer) (at Assets/Scripts/CharacterMovement.cs:318)
CharacterMovement:HitCast (single) (at Assets/Scripts/CharacterMovement.cs:293)
CharacterMovement:Hit_performed (UnityEngine.InputSystem.InputAction/CallbackContext) (at Assets/Scripts/CharacterMovement.cs:278)
UnityEngine.InputSystem.LowLevel.NativeInputRuntime/<>c__DisplayClass7_0:<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType,UnityEngineInternal.Input.NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType,intptr)

line 278:

private void Hit_performed(InputAction.CallbackContext context) => HitCast(hitForce);
```line 293:
```cs
GenHitParticles(hitInfo.point, hitInfo.collider.GetComponent<Renderer>());
```line 318:
```cs
Camera.main.Render();
#

would the render texture somehow be getting reset?

#

I have it stored in the class and never changed so I wouldn't think so.

quartz folio
#

Slightly scary where you're rendering the main camera from, but I won't question that part too much

#

You'll probably have to show where you initialise the RT

#

You should be calling Create yourself if you haven't already

#

(and Release for that matter)

shell scarab
#

yes it is scary. I couldn't figure out a way to get the pixel color from the screen in a different way.

#

would I really need to call Release if I just reuse the same render texture over and over?

quartz folio
#

You use it when you're done

shell scarab
#

it only showed post after post about rendering the camera to a render texture

shell scarab
zenith iron
#

@potent sleet so SQLite works on my Mac, thought you might like to know. I must’ve been doing something wrong with the dll files, gonna have a play around to try and fix it

sweet basin
#

Hey everyone, this might be a beginner-ish problem, so I apologize to put the thread here, but I'm having an issue with the reload function for my gun. I really haven't the clue what the exact issue is so i'll just send the code https://gdl.space/tepivuzino.cs Please let me know if you need any more info, I'll gladly send it

shell scarab
sweet basin
shell scarab
#

you said that you're having an issue with the code but didn't say what the issue was, could you start by saying what the issue is?

#

I know you said you don't know what the issue is, obviously if you did you wouldn't be asking here, but what's happening with it right now?

sweet basin
#

Ahh nvm I reread your question. In any case, nothing happens, the magazine I have stays at 0 once I empty it and the function never happens, and what is supposted to happen is, after the R key is pressed the reload starts, it lasts for "gunData.reloadTime" which I set to be 1,5 seconds and the current magazine should be equal to the overall mag size

shell scarab
#

hmm well first I don't think you need the ?. operator to invoke an Action, could be wrong though.

second, have you put debug log statements in the if statement that gets the reload input to make sure that works?

third, have you tried putting debug log statements in the reload function? Could gunData.reloading be set to true already? maybe it's not getting through that. As for the activeSelf, I'm just going to assume that's true, although you don't need this to access gameObject.

Next, have you put debug log statements in the Reload coroutine? In the code you sent you have a typo, gunData.reloadTIme, I assume it's supposed to be gunData.reloadTime. Also, could that value be very large?

Finally, could gunData.magSize be 0?

#

@sweet basin that's everything I could see that could be wrong, besides the fact you should probably unsubscribe from those events in OnDestroy() or something.

sweet basin
# shell scarab hmm well first I don't think you need the ?. operator to invoke an Action, could...

I sincerely apologize to say this but I don't understand what you mean with the second and third point. I'm quite new to game development and I wasn't too deep into programming before this either so it's really hard to understand. As for the ?. operator, I'm confident it's not an issue because the action before reloading, the one that deals the actual damage to the target, works just fine with the same operator. And as for the fourth point, yes I made a slight mistake with the reloadTime typo, managed to correct it but the issue is the same still.

shell scarab
#

using Debug.Log(object); at various points in the code to print to the console is what I mean, to verify it's reaching there.

sweet basin
sweet basin
shell scarab
#

@sweet basin first, can you send a screenshot of your IDE?

#

are you using visual studio? I want to check if it's a "miscellaneous file" or not.

shell scarab
sweet basin
shell scarab
#

ah ok, so it's not something easy we missed then, compiler would have complained.

#

yea, just try the Debug.Log statements. I would literally just do
Debug.Log(1);
Debug.Log(2);
Debug.Log(3);
....
and so on, and see where it doesn't reach.

sweet basin
#

For every function?

shell scarab
#

no

#

In the code that you sent (I don't know if these line numbers match up to your cs file) I'd put one after line 21, after line 47, after line 49, after line 55, and after line 57.

sweet basin
#

Uhh non of them pretty much

#

I have emptied the mag and I got no info after trying to reload

#

I tried to see if I did the debug wrong by putting one message on the shooting command also, but that one worked just fine and I got the info

#

And so I deleted it

shell scarab
#

so I suppose it's not detecting the reload key

#

you put a Debug.Log() statement inside of the if (Input.GetKeyDown(reloadKey)) if statement right?

sweet basin
#

Yes

shell scarab
#

you're serializing the field, are you sure it's set to R?

sweet basin
shell scarab
#

nonono, in the inspector

sweet basin
#

I mean I did type the KeyCode.R after it

shell scarab
#

when you Serialize the field it exposes it in the inspector, so it could be changed.

#

check the inspector of the object that has the PlayerShoot component

sweet basin
#

Could be cuz of this that I don't have it

shell scarab
# sweet basin

Sorry, I'm a bit confused... by inspector I meant the thing on the right side of unity, as shown in the screenshot you sent here

#

just click on the object that the PlayerShoot component is attached to

sweet basin
#

Yes, but it wasn't there, If I delete the [HideInInspector] I can see the bool element

shell scarab
# sweet basin

yes, but that's not what I'm talking about. I'm talking about this

#

it seems that reloadKey is assigned something else in the inspector.

sweet basin
#

I'm so sorry to bother you like this and lack so much knowledge, but I really am not sure how to check that

#

I just went through every folder and script and I have nothing

#

With reload

#

Ohhhhhh nvm I realised what you were talking about, I forgot to add the PlayerShoot to my gun...

#

I was sure I added it since I added the Gun script also

#

I mean I was sure everything in the inspect was right, so I only focused on the code

#

I see it works now, thank you for all the help anyways, and I'm sorry to trouble you like this

shell scarab
#

lmao

#

so unity uses components. When you create a script by default it can be attached to any game object. I was trying to ask you to select the gameObject that you had added that script to and check the inspector, the panel on the right side of the screen.

sweet basin
#

Yes I know that, I understood later what exactly you meant, but I thought that I had already attached all the scripts

#

That's why I really didn't understand the problem

vague slate
#

I am a bit confused

#

Vector2.SignedAngle gives me 0

#

when I pass: from -17,-8 ; to 0,0

#

am I doing something wrong?

#

I need to get Y look angle from one position to another

cold parrot
vague slate
#

yeah, nvm that

#

I realized

#

I need target direction and current forward

#

instead

steady granite
#

Any idea why this appears when I call DontDestroyOnLoad on referenced object but only after I start play mode more than one time? The first time I start play mode after rebooting Unity, I don't get errors, then I get this 3-5 times at start. Doesn't seem to stop the script though so no impact but still weird...

fathom plaza
#

Hi guys! I have a question regarding coroutines. So assuming I have a code like this:

{
  if(x)
    {
      print("hi");
      x = false;
    }
   else
    {
      StartCoroutine(UpdateX());
    }
}

private IEnumerator UpdateX()
{
  yield return new WaitForSeconds(1f)
  x = true;
}```
#

will the coroutine keep on starting again at the beginning before it could pass the if condition in the Update() function?

knotty sun
knotty sun
#

put the x = true before the yield to stop this, but it will only half the problem

thin aurora
#

So in your case, it will be started as often as is possible in 1 scaled second

#

So assuming you run at a constant 60 fps, and your timescale is unchanged, 60 Coroutines will run at once

#

So this is probably not a good idea

fathom plaza
#

I plan on just putting another bool

knotty sun
#
bool isRunning = false;
private void Update()
{
  if(x)
    {
      print("hi");
      x = false;
    }
   else if (!isRunning)
    {
      StartCoroutine(UpdateX());
       isRunning = true;
    }
}

private IEnumerator UpdateX()
{
  yield return new WaitForSeconds(1f)
  x = true;
   isRunning = false;
}
fathom plaza
#

yea exactly what im doing now lol

knotty sun
#

perfect

fathom plaza
#

been stuck on a bug regarding input for about an hour

#

and I had to act like a controller for an hour to understand it

#

thanks for the help though!

knotty sun
#

@fathom plaza tbh you could just do

private void Update()
{
  if(x)
    {
      print("hi");
      x = false;
      StartCoroutine(UpdateX());
    }
}

private IEnumerator UpdateX()
{
  yield return new WaitForSeconds(1f)
  x = true;
}
twin vector
#

Hello, I don't know if this topic should be in general or some other code based channel, I'm looking for any source that will help me to implement Fog of War, something like Warcraft 3 Fog of War, best practices etc 🍻

twin vector
#

Thanks, I will ask there

mint vector
#

any better way to implement this?

fathom plaza
#

So basically, I want the coroutine to start first

simple egret
timid crater
#

Hello, Why does agent.remaining distance always returns 0? Has anyone ever encountered such thing? There's no errors, no issues with the gameObject and the target, the agents are set correctly

plucky fractal
#

if i have multiple colliders can i know which one was triggered?

timid crater
plucky fractal
#

well yes, but if i have one on right and one on the left can i know when the left one is triggered?

#

or should i make defferent objects per side

simple egret
#

OnTriggerEnter, you can't

timid crater
simple egret
#

Probably, with each one having a script that relays which one collider to the same script

#

And you can use multiple colliders per object

plucky fractal
#

i see PepoG

timid crater
#

Would they all fire?

simple egret
#

If they have the exact same bounds, yes

timid crater
heady iris
#

Group the colliders by meaning on child objects

#

so if three colliders are all hitboxes, put them all on a child object

#

and add a component that reacts to collisions accordingly

mighty juniper
#

Hey, anyone got any idea how I could make the highlighted tiles on movable spaces for the rook look better? I'm tryna figure something out but cant get something looking good as my artistic skills is non existent

mighty juniper
#

hm, that could be an option, no idea how to make one of them though so i'd have to do some research

timid crater
# mighty juniper hm, that could be an option, no idea how to make one of them though so i'd have ...

Hey Guys! Welcome back to another CG Smoothie Video! In this video I'm bringing you guys a new Unity Game engine tutorial! This time, we're learning how to use the unity game engine to make 3d outlines around characters and objects in your game using the Unity Shader Graph! I think this is one of the BEST Outline tutorials out there! If you guys...

▶ Play video
#

Try these if you'd like

mighty juniper
steady moat
#

Transparent Red/Green ?
Arrow ?
Single Dot ?
Transparent Mesh ?
Single Case ?

mighty juniper
mighty juniper
heady iris
#

very low poly models will not play nice with an outline shader

#

at least, ones that work by pushing faces out along their normals

timid crater
mighty juniper
heady iris
#

I know of a good HDRP outline custom pass

#

not sure about URP tho

mighty juniper
#

Yeah I only really know the absolute basics for shader graphs to be honest, never really dove into it much

heady iris
#

What you COULD do is make a separate mesh for the outline

#

do you know much about Blender/3D modeling in general?

mighty juniper
#

i mean its not really a problem, i dont really need an outline anymore for pieces. It was just an idea for the tile highlights

mighty juniper
#

this is what i have for highlighting pieces now on mouse hover

#

which looks fine so im not bothered about changing that

heady iris
#

ooh yeah, that's nice

#

Also, if you used smooth shading (when exporting the models), the shader would work

#

my understanding is that, to make sharp edges, you have to actually make the faces separate