#archived-code-general

1 messages ยท Page 351 of 1

fickle birch
#

I incorrectly assumed everybody has low attention spans

leaden ice
#

Use a LineRenderer and raycasts

main oxide
#

bro can somebody please make me an anticheat for my game people have my apk and have all moderator items

fickle birch
# leaden ice Use a LineRenderer and raycasts

I am using Raycasts, I'm mainly trying to write the logic for the script to scale down the Laser Sprite if the ray hits an Object in the middle that's not a Player

If I use Line Renderer, will I be able to use it with my Sprite?

leaden ice
fickle birch
# leaden ice > I'm mainly trying to write the logic for the sprite to scale down the Laser Sp...

I tried, but I'm not sure if it's correct, the output is crazy


    void UpdateLaserBeam()
    {
        // Cast a ray from the laser spawn point to detect ground objects
        RaycastHit2D hit = Physics2D.Raycast(spawnPoint.position, spawnPoint.right, 100f);
        if (hit.collider != null)
        {
            float distance = hit.distance;
            GameObject laserBeam = transform.GetChild(0).gameObject;
            laserBeam.transform.localScale = new Vector3(distance, 1, 1); // Scale the laser beam to the distance
            laserBeam.transform.position = spawnPoint.position + spawnPoint.right * distance / 2; // Position the laser beam correctly
        }
        else
        {
            GameObject laserBeam = transform.GetChild(0).gameObject;
            laserBeam.transform.localScale = new Vector3(100f, 1, 1); // Scale the laser beam to the maximum detection range
            laserBeam.transform.position = spawnPoint.position + spawnPoint.right * 100f / 2; // Position the laser beam correctly
        }
    }```
fickle birch
#

Like it jitters a lot because it's being called on Update() and it's like the 2d version of z fighting

leaden ice
#

Can you elaborate on what you mean by "jittering"?

#

maybe show a video

fickle birch
leaden ice
#

that doesn't mean much to me. A video would be better

fickle birch
#

Okay, one sec pls

leaden ice
fickle birch
#

Yes

leaden ice
#

Your raycast is hitting the laser itself

#

you're not using a layermask

#

use Debug.Log to diagnose issues like this

#

You need to be checking what your raycasyt is hitting

fickle birch
#

Ohhh

leaden ice
#
if (hit.collider != null) {
  Debug.Log($"Hit {hit.collider.name}");```
fickle birch
#

๐Ÿ™ Thank you, I'll try

leaden ice
#

If it says "Hit object" in the console then you have a GameObject in the scene named "object", and that's what it's hitting.

gray mural
#
Tools.current = Tool.View;

When called from Editor.OnSceneGUI, why does this line throw the following error and how would I fix it?

The targets array should not be used inside OnSceneGUI or OnPreviewGUI. Use the single target property instead.
fickle birch
#

But it's not working correctly still

leaden ice
fickle birch
#
RaycastHit2D hit = Physics2D.Raycast(spawnPoint.position, spawnPoint.right, 100f, LayerMask.GetMask("Ground"));```
#

The Objects it is supposed to be blocked by are all on LayerMask ground

leaden ice
#

ok so... what's going wrong with it now?

hidden flicker
#

How could I subdivide a mesh at runtime? I want to have a square prism and be able to subdivide it into x amount of smaller squares

fickle birch
#

Doesn't scale like intended

leaden ice
#

Show the code, show the console

#

play the sound from a different object, or don't destroy the object until the sounds is done.

#

Or just use AudioSource.PlayClipAtPoint

barren musk
#

does anyone know how to make a gun shoot?

supple ginkgo
#

yo

fickle birch
# leaden ice ok and... are you logging things? What is it logging?

https://hastebin.com/share/iqalohasuh.java

I'm not logging anything because the tracking and rotating is working, it's just the sprite scale adjustment that is buggy, which you recommended to debug now and I complied.

The problem is probably with the way the function is being called in Update or something, or maybe the logic for the scale adjustment is wrong itself

leaden ice
#

You should probably also log something when it misses

#

see what happens when the jittering is going on

fickle birch
#

Okay

leaden ice
#

what's null

fickle birch
# leaden ice what's null

It causes a Null reference exception when the ray misses because it's not hitting anything

If it is handled, it prints("Null")

leaden ice
#

I meant print something like Debug.Log("The ray hit nothing");

fickle birch
#

Sorry I haven't slept much today

#

It did print null, is there a way to see the Ray as debug line? I will remove the scaling logic and see what it's actually hitting?

gray mural
fickle birch
#

Thank you

gray mural
#

And don't forget about its parameter, time

reef garnet
#

Just started a new project and Unity is being funny with me, any time I save in Visual Studio unity recompiles which is normal, the annoying part is that it displays over Visual Studio and for a chronic Ctrl+S user like me it gets annoying very quick, is there a way I can stop this?

gray mural
reef garnet
#

Yeah after a second or 2

gray mural
#

This has never happened to me

reef garnet
#

First time for me and it's a Unity Version I was working on in another project

gray mural
#

What version?

reef garnet
#

2022.3.32f1

gray mural
reef garnet
#

ok

indigo tree
#

For player state logic, is it better to use a single data structure or classes that inheritance from each other to represent states?

leaden ice
#

If it's relatively simple, just an enum and a switch statement are good enough

indigo tree
#

I am currently just searching through this to find the state I want but I am worried that this won't be sustainable.

leaden ice
#

when you say "searching yhrough this to find the state" are you describing something you are doing as a developer to make code changes?
Or are you describing something your code is doing?

spark stirrup
#

whats the best way to save and load gameobjects from a scene while keeping all of their scripts and variables?

leaden ice
#

for loading, do the reverse

indigo tree
leaden ice
#

you do mean just accessing the dictionary by the key right?

#

Not actually "searching through the dictionary"

indigo tree
leaden ice
#

also latter*

#

ok I mean... seems fine to me so far

indigo tree
#

What I am more worried about it how I store the state data rather than how I obtain it.

#

For non constant ones, I'll probably have to create new states directly rather than obtaining it through the dictionary. Such as states that represent unique moves per characters.

#

So I can construct them or use a class for parameters.

fickle birch
#

@leaden ice Thanks for trying to help me.

Instead of spending 2-3 hours on this problem, I should have just reused my Grenade/Missile Launcher Prefab and increased the fire rate and Missile Sprite

#

๐Ÿคก ๐Ÿ”ซ

flint panther
#
                    Vector3 handsDirection = other.Hand.position - Hand.position;
                    targetRotation = Quaternion.LookRotation(handsDirection);```
#

Very simple yes

#

Why it does this

#

The gun seems to flip around when going to a certain angle

#

I believe that angle is precisely aligned with the negative z axis

#

Uh yeah?

#

Any of your public spell derivatives will automatically be able to access the base spell variables

#

If your IceSpell inherits from Spell you do not need to get any component

#

It is a spell

#

It can access the spell variables

#

Yes. If another script is accessing icespell, it can access all of the public base spell variables too

#

I'm confused. Can you share what this is for

#

Example

#

And I am telling you, that your spellCaster script can just access the spell variables
If you're storing the prefs as gameobjects, then don't do that, store them as spells

#

I think so. I wouldn't do that though

#

You can just store it as a list of spells, and it will spawn the prefab and give you your spell automatically

queen saffron
#

Hi all ๐Ÿ˜„
I'm doing a VR project that needs manipulation over meshes in runtime, i decided to use ProBuilder plugin for that.
now i'm facing an issue regarding extrude within face normals

#

it says my face normals are Null

#

so i computed faces normals once again and tried to add then but..
pbMesh.normals = normals; gives Property or indexer 'ProBuilderMesh.normals' cannot be assigned to -- it is read only ERROR

main oxide
#

my game got modded by an apk how do i prevent this

knotty sun
clear oriole
#
public Vector2Int GetTileGridPosition(Vector2 mousePosition)
    {
        positionOnTheGrid.x = mousePosition.x - rectTransform.position.x;
        positionOnTheGrid.y = rectTransform.position.y - mousePosition.y;

        tileGridPosition.x = (int)(positionOnTheGrid.x / (tileSize * playerUICanvas.scaleFactor));
        tileGridPosition.y = (int)(positionOnTheGrid.y / (tileSize * playerUICanvas.scaleFactor));

        return tileGridPosition;
    }

Found the solution, it was fairly simple, and now i can just pass the raw mousePosition

spare island
#
            // recursively find the root object
            Transform root = transform;
            while (root.parent != null)
            {
                root = root.parent;
            }

            // set the root object to not be destroyed on scene change
            DontDestroyOnLoad(root.gameObject);

is this a dumb way to do this?

#

i want to force whatever root object the component is attached to be ddol

#

even if nested

lean sail
#

oh i got confused by the name

spare island
#

is that the same thing?

lean sail
#

you can directly access the root

spare island
#

it says the topmost transform?

#

i would assume that means the first object in the hierarchy of the scene the component is in not the root object that the component is attached to

lean sail
#

did you read the 2nd line of the 2 lines that were on that page

#

(This never returns null, if this Transform doesn't have a parent it returns itself.)

spare island
#

yes i did read it i'm just not sure its what i want

#

if you're saying it is ill try it though

#
            DontDestroyOnLoad(transform.root.gameObject);

so i can do this?

#

and that will select the highest object like this

lean sail
#

yes its the same as what you were doing in your while loop

#

though honestly it seems weird that a child object is doing this logic

spare island
#

well the alternative is putting a script on the HUD where its only purpose is to make it ddol

#

currently the "HUD" object is just a canvas with no scripts

#

i tried the line of code, didn't work nvm forgot to recompile

sly chasm
spare island
#

im assuming you're using built in unity navmesh and controllers and such

spare island
#

unity docs says that instantiating is equivalent to duplicating with ctrl + d but thats obviously not the case

indigo tree
spare island
#

set to play on awake

#

only plays sound if i drag in or duplicate with ctrl + d

#

awake must run before the object is instantiated, but if thats the case how does duplicating it work

somber nacelle
#

is the audio resource actually assigned to the prefab or does it get assigned after you instantiate it?

spare island
#

its actually assigned in the prefab

somber nacelle
#

show your code that instantiates it

indigo tree
spare island
#

here is the prefab

#

both automatic and manual didnt work

indigo tree
spare island
#

let me try with a normal audio clip

somber nacelle
#

show ๐Ÿ‘ the ๐Ÿ‘ code ๐Ÿ‘

spare island
#
        public void CreateNotification(Notification notification)
        {
            var notifGo = Instantiate(_notificationPrefab, transform);
            var notifText = notifGo.GetComponent<INotificationText>();
            notifText.Set(notification);
        }
#

for some reason there is a difference between instantiating and using the editor to create a new instance

somber nacelle
#

what does that INotificationText.Set method do

indigo tree
spare island
#

nothing crazy that should affect how it instantiates

indigo tree
#

๐Ÿค”

spare island
#

gonna check docs on random audio container..

somber nacelle
#

well it's definitely odd that this is happening. one thing you could do that would not only solve this issue, but also reduce your performance impact is to have just one audio source for these and just PlayOneShot on that audio source when you instantiate (or retrieve from a pool so you reduce the number of objects being created/destroyed) the object

spare island
#

well tbh i think theres a way to just play a sound without an audio source but idk how that would work with random containers

indigo tree
somber nacelle
#

but if you can replicate this issue in a blank project then submit a bug report because that behaviour shouldn't be happening

somber nacelle
spare island
#

"fixed"

somber nacelle
#

and are you actually using .11

spare island
#

sigh no

#

im using .10f1

#

im actually being trolled i literally just updated ๐Ÿ˜ญ

somber nacelle
#

well then you need to update to get the fix

spare island
#

i guess its better than finding the bug and then it not being fixed yet

cosmic rain
#

That's why you use LTS for solid projects

somber nacelle
#

i mean, bugs can happen in LTS versions too

spare island
#

tbh i've had less problems in the unity 6 preview than i have in LTS

cosmic rain
#

True, but it's more likely to run into a bug in a beta build

spare island
#

i want to see when this update came out

#

because i quite literally updated less than 24 hours ago

somber nacelle
#

.11 was released on the 17th

spare island
#

why did it download 10f then..

#

i went from 2f1 to 10f1

#

maybe outdated notification? (i downloaded from the update notification in the editor)

somber nacelle
#

because that's the version you selected obviously. if you hadn't restarted the hub between the time the new version was released and the time you updated then perhaps the hub just didn't see the newer version

spare island
#

that might be it i haven't shut down my computer in a couple of days

#

finally an issue that wasn't a complete skill issue on my part though

flint dagger
#

I'm trying to get the white cube to follow the cursor on the screen but for some reason it's on an offset. Does anyone know how I can make it actually cast from the correct position?

dusk apex
flint dagger
#

Here's an example log. Original mouse pos, mouse pos in the rect on the desktop, and the final hit pos.

leaden ice
#

After converting it to a normalized position

#

Within the RenderTex

junior wind
#

Is there something wrong with this snippet?
The gameobjects I'm trying to create are being spawned, but they're invisible. The base prefab is showing up appropriately and it's always z = -1 (in 2d), which works for similar prefabs I've made.
I really have no idea why I can't see them

    private void OnDestroy()
    {
        if (currentLife < totalLives)
        {
            Instantiate(iceSpikePrefab, transform.position + topOffset, Quaternion.Euler(0, 0, 35));
            Instantiate(iceSpikePrefab, transform.position + bottomOffset, Quaternion.Euler(0, 0, -35));
            currentLife++;
        }
    }
leaden ice
#

Likely they're just either not within view of the camera or just behind something else

junior wind
#

I've tried that. Positions are where they should be, they're just invisible. It's driving me nuts ๐Ÿคฏ

leaden ice
flint dagger
leaden ice
#

And no that doesn't mean .normalized

#

It means dividing it by the width/height of the Rect

flint dagger
#

Oh I see

pine notch
#

anyone got a tut for this https://www.youtube.com/watch?v=6PSLfRsN89g
but with OVR stuff

What up guys, in this video I'm going to show you how to make a really cool Hand Menu that will follow your left hand and only show when your palm is facing up ! Super handy to let the player easily tweak something without being too intrusive. Hope you guys will enjoy the tutorial. :)

โค๏ธ Support on Patreon : https://www.patreon.com/ValemVR
๐Ÿ”” S...

โ–ถ Play video
#

i am trying to add a hand menu like this but in a mixed reality game

flint dagger
digital skiff
#

Hello, not sure if this is quite the right place but i think its my best bet?
Im making a mod for a game which reads custom assetbundles and .dlls to allow additional usermade content to be added to it. Im wondering how i can include code from a unity package into a dll to submit to the game? I am able to do it with assemblydefinitions using custom scripts i write myself.

autumn cedar
#

Pretty random but... in variables declaration, do you guys use private keyword with private members or just write them out like.. Obviously there are 2 approaches:

private RigidBody rb; // Clearer

Rigidbody rb; // Concise  

So, what do you guys say is the best convention?

digital skiff
#

ah good news the game doesnt care about package code being included

west lotus
autumn cedar
west lotus
#

There is no spoon. Conventions exist so that larger teams can work together more efficiently. And each team evolves its conventions over time to best fit them

autumn cedar
#

Hmm got it. Thank you! ๐Ÿ˜„

foggy elm
#

I used to prefix with the underscore character but it looks pretty ugly, so I now prefix private member variables with m_

dusk apex
#

I'm assuming you meant _ and m_. You'd just use what the team is comfortable with - which may change with every team.

foggy elm
#

Yep

minor patio
#

lightning not working in 2d

#

I set it up correctly tho (wrong but like i followed a tut)

#

installed urp from package manager, made an asset, added a 2d renderer to the asset,

sleek bough
#

This is a code channel

minor patio
#

oh mb

#

where do I ask abt ts damn

sleek bough
#

And post actual details not a rant

minor patio
hushed wadi
#

Hi guys. Is this the appropriate place to ask how to achieve something specific with cameras, possibly camera stacking?

hushed wadi
gray mural
wicked crystal
#

Hello guys, I want to vibrate an object left and right according to its pivot.

gray mural
ebon leaf
#

how can i change the pivot point for the default triangle sprite. wont let me edit it in sprite editor cause its within unity and i dont feel like using an actual sprite just to test out an idea but i can see that the pivot is in the center by default however i cant move it

leaden ice
#

Edit the copy

tawdry forge
#

Hello, I was wondering while coding if GetComponent() is a costly action or not ? Should I cache the result as much as possible ?

ebon leaf
minor patio
#

can someone help me with this pls,

void Shoot()
{
    if (HandHolder.childCount == 0) return;
    HandHolder.GetComponentInChildren<HandScript>().Shoot();

    Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector3 direction = (mousePosition - shootStart.position).normalized;

    RaycastHit2D hit = Physics2D.Raycast(shootStart.position, direction, weaponRange);

    GameObject trail = Instantiate(bulletTrail, shootStart.position, HandHolder.rotation);
    TrailScript tr = trail.GetComponentInChildren<TrailScript>();
    if (hit.collider != null)
    {
        tr.SetEndPos(hit.point);
    }
    else
    {
        Vector3 endPosit = shootStart.position + direction * weaponRange;
        tr.SetEndPos(endPosit);
    }
}

my issue is that it shoots to a certain position, instead of shooting to the mouse position

#

I first tried making it shoot to it's forward by using shootStart.forward

#

but it only shot to a certain point (always the same point no matter where I moved

leaden ice
gray mural
#

My Tilemap is really huge, despite having, as I think, a single Tile. Any way to make it smaller?

ebon leaf
#

it works fine the first time but later on it doesnt wait the full 2 seconds, i can see it throught the editor with serialized field barely switching to -1 for like a milli second instead of waiting properly

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragonFlame : MonoBehaviour
{
    public float flameTurnOnTimer;
    [SerializeField] float flameDirection = 1;

void Update()
    {
        StartCoroutine(DirectionSwitcher());
    }

IEnumerator DirectionSwitcher()
    {
        yield return new WaitForSeconds(flameTurnOnTimer);
        flameDirection = -1;
        yield return new WaitForSeconds(flameTurnOnTimer);
        flameDirection = 1;
    }
simple egret
knotty sun
#

Also WaitForSeconds is framerate dependent

ebon leaf
simple egret
#

That's a solution, and you can put a loop in the coroutine method so it runs forever

ebon leaf
#

i want the courotine to repeat

#

nice, thx man

rigid island
#

IEnumerator Start()

ebon leaf
#

im not too good at making loops but the one i made was the classic

for (int i = 0; i < 2; i++) {

}
simple egret
#

I have to go, someone else will take the lead

ebon leaf
#

alr cya

rigid island
#

"its all buggy and doesnt work" is not very descriptive anyway

knotty sun
ebon leaf
knotty sun
#

time to learn

ebon leaf
#

agreed xd

rigid island
#

for(;;)

swift falcon
#

Visual Studio automatically fills in loops on double Tab, its very good

flint panther
rigid island
#

too much coffee?

flint panther
#
                Vector3 handsDirection = other.Hand.position - Hand.position;
                Vector3 gripsDirection = other.grabPoint.position - grabPoint.position;
                float angleAdjustment = Vector3.Angle(root.forward, gripsDirection); // Angle needed to bring it straight0
                Vector3 relativeUp = Vector3.Cross(handsDirection, Hand.right);
                Vector3 targetDir = Quaternion.AngleAxis(angleAdjustment, -Vector3.Cross(root.forward, gripsDirection)) * handsDirection;
                targetRotation = Quaternion.LookRotation(targetDir, relativeUp);```
#
            (targetRotation * Quaternion.Inverse(grabPoint.rotation)).ToAngleAxis(out float angle, out Vector3 axis);
            rb.angularVelocity = angle * Mathf.Deg2Rad * axis.normalized / Time.deltaTime;```
flint panther
rigid island
#

just enough to use them in unity

#

this is however too much math for me this morning lol

flint panther
#

Me too

flint panther
rigid island
flint panther
#

What would it do

#

Well, that did not fix it

rigid island
#

idk I normally do it for direction. Idk if matters here prob nont

flint panther
#

It looks like when the rotation goes to a certain point, it tries to do 360 degrees the other way

rigid island
#

Debug values, make sure its not going to 0 vector

spare island
#

Are there issues when invoking events from async functions?

#

because for the last two days i've had various issues with events just not being invoked correctly

#

the only thing i can think of is that maybe its because im invoking from inside async stuff

rigid island
#

should not be issue. are you sure that part of the code is reached

ivory smelt
#

Hello, im having an issue that is giving me a headache, my game runs without errors or warnings iside editor, but once I make a build to test a few things, this is what I see when opening the game. Music is playing but as you can see the main menu aint loading and IDK what might be causing it.

#

Using default render pipeline and a very light project

knotty sun
#

and the target platform of the build is?

ivory smelt
knotty sun
worn ginkgo
#

im coding stairs in my game,
for now just going down stairs
essentially if the space between my player and the ground is within a threshold, the player isnt already grounded, and the player isnt trying to jump,
then the player teleports down the distance,
the one issue with this is that the player will always teleport the last little bit at the bottom of a fall,
how do i fix this?

hexed geode
#

Unsure where this goes, but, if I wanna make a Play of the Game system like Overwatch in my game (where after a match, a recording of the best moment in the game plays for all players from the PoV of that player), would the easiest way to do it is to just record an actual video from the PoV of the player and keep it in a buffer or some other way, such as a "demo" like overwatch itself does it

ivory smelt
worn ginkgo
knotty sun
hexed geode
worn ginkgo
ivory smelt
#

Everything seems fine

knotty sun
ivory smelt
#

Like, putting a Debug.Log() everywhere ?

#

But whats the point if it works OK inside Editor

knotty sun
ivory smelt
#

shoulnd it be some config in project settings or smth?

knotty sun
#

that is what we call debugging

ivory smelt
#

Ikr, but there is literally no place where ir could be failing, I tried removing every scene but the main menu one, which is a simple image with play and quit buttons, and it still fails

knotty sun
#

you do realize that that statement makes absolutely no sense whatsoever

#

'it can not be going wrong' but 'it is going wrong'

hexed geode
ivory smelt
ivory smelt
hexed geode
ivory smelt
#

like, all the project not just the assets

#

oh wait i misunderstood

ivory smelt
hexed geode
ivory smelt
#

What is going on

hexed geode
ivory smelt
#

this one also works and is the same as the original

civic egret
#

in unity, how can I make the navmesh agent not pick the shortest path to a destination point? Right now its kinda hugging along the wall until it gets to the point

spare island
#

This is the same pattern that is used to make things like "undo" and "redo" functions in applications

#

To put it simply, you're storing the parameters of a method in an object and then storing that object

#

so instead of

Move(Vector3 vector, float speed) etc

it'd be more like
Move(MoveCommand command)

obviously, this will require a lot of refactoring if you haven't built your game up to the point to be able to implement this pattern

hexed geode
spare island
#

or at least you should

#

also im not sure about the legality of a play of the game system, i believe blizzard has it patented

hexed geode
hexed geode
spare island
#

so if your system works too similarly it could infringe (im not a lawyer though and this is not legal advice)

frozen ridge
#

hey guys, i'm interested in behavior trees and i plan to use them for an ecological simulation. What i'm curious about is, will each entity have an instance of the BT?

Let's say i have 50 foxes, will each fox tick its own bt or is there a better way to do it?

spare island
#

Entity-component systems

#

Instead of each entity controlling its own behavior, there is one instance that controls all of them - the entities only hold data

#

at least thats my understanding

spare island
#

so you can then recall those commands

hexed geode
frozen ridge
#

how can i implement complex behavior with ecs systems

spare island
hexed geode
spare island
#

they quite literally just replay inputs

hexed geode
#

Is that how Demos in like, valve games or overwatch work

spare island
#

I dont know how overwatch works but source games have a recording/replay system i believe

hexed geode
#

Also is this in any way useful other than just making recordings of games

spare island
#

where you can replay exactly a player's actions from the console

spare island
#

Then think about how you're going to get that video to everyone else

hexed geode
spare island
#

for a game like content warning this is a feasible idea because its such a small scale

frozen ridge
#

command pattern is useful for designer tools as well, like imagine when you do ctrl+z when you want to revert in photoshop/aseprite or whatever

hexed geode
#

Although I suppose you wouldn't need that much factoring?

spare island
#

which i think can be automated

hexed geode
spare island
#

i mean tracer wouldnt work without commands

hexed geode
#

Oh true

spare island
#

well i guess they could just be storing her position 3 seconds ago but idk

frozen ridge
spare island
#

not only does that allow for highlights, but you can have a full replay system

hexed geode
spare island
#

where you can watch every single thing that happens

frozen ridge
#

for league of legends, i think it uses the commands to literally play the game again if you watch your saved game

spare island
spare island
#

then interpolating - but i doubt that

#

from what ive seen while playing tracer it replays very tiny movements

hexed geode
#

Does this mean that quite a lot of games actually use commands?

spare island
#

its one of the fundamental programming patterns so yes

frozen ridge
#

whenever you can rebind your game controls it means command pattern is being used

hexed geode
#

Thank u for telling me :)

frozen ridge
spare island
#

it is a very good book and its completely free

hexed geode
spare island
hexed geode
# spare island is this your first multiplayer game

Second try, first try at a multiplayer game ended up with me making a Lobby system way after I made a lot of the game, created many game-breaking bugs that I did not have the knowledge to fix so I gave up

spare island
hexed geode
spare island
#

my tools are made specifically for unity services

#

i'd also recommend against photon from my own experience + their pricing

hexed geode
#

Are there any better multiplayer solutions for unity

spare island
hexed geode
spare island
#

once you release you'll need to pay

#

you have a couple of choices

hexed geode
#

I'll need to look into that then damn, surely this only applies to paid games?

spare island
#

NAT punchtrough,
Relay,
Steamworks are the best options for broke indie devs imo

spare island
#

swear im not being paid to shill unity services

#

i wish i was i'd love to be paid for anything i do -v-

worn ginkgo
#

how would i get the collision data like shown here?
https://youtu.be/ILVUc_yV24g?si=q-JPxuCLjPPnLUge&t=486

Letโ€™s talk about stairs, why they suck in games, and what can be done about that.
You wouldnโ€™t think stairs are that hard for video games, until you see some of the bugs they can cause
Check out a live demo of the OpenKCC Project here - https://nickmaltbie.com/OpenKCC/

Chapters:
00:00 Getting High
01:18 What are Stairs?
02:33 Hiding the Problem...

โ–ถ Play video
hexed geode
spare island
#

Might work with NAT punchthrough, haven't tried

hexed geode
#

What is Relay?

#

...or NAT punchthrough

spare island
#

Relay connects players to eachother through a relay, one of the players is a host players and the others are clients

#

It doesn't require port-forwarding

#

NAT punchthrough is basically a hacky way to get around port forwarding

#

sometimes works sometimes doesnt, depends on the network

#

you may see in some games they talk about your "NAT type"

hexed geode
#

So NAT punchthrough/Relay is what does the connecting and something like Mirror is what makes your code work? I'm sorry I'm pretty new to this

spare island
#

something like Mirror handles the netcode

#

so how the game works

#

Relay is the transport layer, which is what gets the connection going basically

hexed geode
#

Ye exactly, makes sense

spare island
#

i've taken a class on networking and got a CISCO certification and i still get intimidated by all the words

#

I think that relay would be the "Transport" and "Session" layer here
and Mirror handles presentation and you handle the application

#

this probably is no longer related to code though

hexed geode
hexed geode
spare island
#

So about 2 weeks ago

hexed geode
#

Oh damn

spare island
#

Mirror support is iffy

#

you have to download a random package off of github then take some files out of it, then you have to modify those files because they don't compile, and blah blah blah

#

the solution they give to connect relay to mirror just straight up didn't work for me when i tried it

#

so i gave up and used relay and unity netcode* which are in the same ecosystem

hexed geode
#

Would you recommend I use that then?

spare island
#

whats your networking budget

hexed geode
spare island
#

relay + unet would be best then

hexed geode
#

Wonderful, thank u

spare island
#

I'd love to save anybody the time from wrestling with trying to get this stuff to work

hexed geode
#

Thank you a LOT
I'll start working on the project in a few days :3

flint panther
#

...unet?

#

that is deprecated for like a decade

fleet gorge
#

terrible practice but I used python flask for it once

#

its really easy to recreate whatever photon does with python flask

#

but youre using what's supposed to be a rest api to make multiplayer which is bad, terrible

#

was a fun learning experience but theres a lot of Websocket packages for c#

oblique spoke
thin hollow
#

I have a bit of a problem with my AI system.
currently, my system has two components per npc, SensesComponent that's tasking with surveying the world and deciding which NPCs can be seen by this NPC, and AiBrain component, which is tasked with making all the decisions.

I think I remember hearing that classes are always get passed around as instances instead of copies, so I decided to let SensesComponent to store seen NPCs in a List of such class called AITargetObjectReference. It contains reference to the npc object, a couple of other variables, and a variable called freshness that gets increased by the SenseComponent when the NPC is in sight and decreases when it is not - I decided to emulate inertia of senses that way (AI doesn't forget enemy the second it turns around the corner, nor does it notice it instantly when it appears).

now the problem is that when I pass the result of the sensing to AiBrain component - the list contents apparently gets passed as a copy, not as an instance:

// in SensesComponent.cs
        [SerializeField][ReadOnly] internal List<AITargetObjectReference> potentialTargets = new();

...

internal List<AITargetObjectReference> GetSensingResults() => potentialTargets;

It's being received in the Brain component thusly:

//in AiBrain.cs
  private void ObtainTargets()
  {
      if (_sense == null) return;

      List<AITargetObjectReference> localactors = _sense.GetSensingResults();
      listOfEnemies.Clear();
      listOfFears.Clear();
      foreach (AITargetObjectReference target in localactors)
      {
        ...

And the issue I noticed is that targets that are in the AiBrain do not update their freshness, meaning they remain as "seen" indefinitely.
How can this be remedied?

fleet gorge
#

idk most of my work with Photon is just using RPC and Photon View

fleet gorge
thin hollow
#

Should I make it public then, maybe?

wide terrace
thin hollow
#

I do remember that structs are always get passed around as copies

wide terrace
#

Yeah that's strange. List is class, so it's definitely passed by reference already... Hmm

wide terrace
thin hollow
# wide terrace Could you elaborate on the list items' `freshness` values changing? Everything y...

Sure, it's handled in the SensesComponent :

foreach (AITargetObjectReference actor in nearbyActors)
{
    ... // calculations of bools are omitted

    if (inRange && !ignore && inFOV && inLOS)
    {
        if (!potentialTargets.ContainsObject(actor))
        {            
            if (actor.pawnType != EAiTargetType.Player)
            {
                //general case, notice object after a set amount of time has passed
                if (actor.CheckAndIncreaseFreshness(awarenessIncreaseRate))
                {
                    recentlySpottedTargets.Remove(actor);
                    potentialTargets.Add(actor);
                }
            }
            else
            {
                //case for player, awareness acuteness varies according to difficulty
                if (actor.CheckAndIncreaseFreshness(awarenessIncreaseRate * difficultySpike))
                {
                    recentlySpottedTargets.Remove(actor);
                    potentialTargets.Add(actor);
                }
            }
        }
    }
    else
    {
        if (potentialTargets.ContainsObject(actor))
        {
            if (actor.CheckAndReduceFreshness(awarenessDescreaseRate))
            {
                recentlySpottedTargets.Remove(actor);                
                potentialTargets.Remove(actor);
            }
        }
    }
}

The CheckAndReduceFreshness and CheckAndIncreaseFreshness methods modify the freshness of the object in the list (and return a bool).

chilly surge
thin hollow
chilly surge
# thin hollow Some of the nesting is indeed probably unnecessary, but I leave it in as it make...

Are you aware of guard clauses? Instead of:

if (potentialTargets.ContainsObject(actor))
{
    if (actor.CheckAndReduceFreshness(awarenessDescreaseRate))
    {
        recentlySpottedTargets.Remove(actor);                
        potentialTargets.Remove(actor);
    }
}

You could rewrite it into:

if (!potentialTargets.ContainsObject(actor))
    continue;

if (!actor.CheckAndReduceFreshness(awarenessDescreaseRate))
    continue;

recentlySpottedTargets.Remove(actor);                
potentialTargets.Remove(actor);
wide terrace
# thin hollow Sure, it's handled in the ``SensesComponent`` : ```csharp foreach (AITargetObjec...

Okay cool ๐Ÿ‘

I guess I'm mostly just wondering about the sequencing of these methods. Like ObtainTargets() will always grab a fresh reference to list, and then (presumably) operate upon it immediately and discard the reference. Even if a list was a value type, I don't see how ObtainTargets() could ever be retrieving outdated data. And unless there's some sort of asynchronous code or jobs involved here somewhere, it's not like the items in the list would be changing during a single invocation of ObtainTargets()... You could even verify that it's the same list at any point within ObtainTargets() via a reference equality check - _sense.potentialTargets == localactors.

Where in AiBrain/ObtainTargets() are you expecting to see different values? Is ObtainTargets() invoked regularly? Short of asynchronous shenanigans, the only thing I can think of is ObtainTargets() just not running again after the freshness values have been updated

thin hollow
#

ObtainTargets is runned from the Update() (though I thinking about moving it into Invoke, since it is probably a bit excessive to update targets every frame)
The discrepancy I see is that the AiBrain and SensesComponent run pretty much independantly from each other (the only time Senses call Brain is either when it detects HeardSound event, or decides that something has bumped into the NPC), the AI Brain calls ObtainTargets, and after that decides which target in the list it needs to held as a priority - so the list gets sorted by a variable in the object, and the top result gets assigned to a variable currentAttentionTarget. And when it gets to the said variable - it isn't updating anymore.

#

Hm... maybe it's the sort function that turns reference list into a copy of a list?

 listOfEnemies.Sort((x, y) => x.importance.CompareTo(y.importance));
 listOfFears.Sort((x, y) => x.importance.CompareTo(y.importance));

Those lists are separate variables in the AiBrain, that have contents added to them from localActors prior to sorting code.

wide terrace
flint dagger
#

Sorry I brought this up yesterday but I still haven't been able to solve it T_T the white cube is supposed to follow my mouse in the computer but for some reason it's at a weird offset. Does anyone know what could be causing it? This damn thing has taken like 6 hours and I've made no progress.

thin hollow
raven orbit
#

how can i make my screen move side to side whenver the player is walking?

#

i just need a general idea

wide terrace
thin hollow
flint dagger
raven orbit
#

whenever the player is moving i want the camera to go left and right if that makes sense

#

thank you

spring creek
#

Dang. Looked like it doubleposted so I deleted one and it deleted both.
I had suggested moving the camera. Looks like you saw it haha

raven orbit
#

i only saw one it may have been a glitch for you, but still thank you

mossy valley
#

Why can't I see my OnPointerClick function in my Event Trigger -> Pointer Click -> Function?

using UnityEngine;
using UnityEngine.EventSystems;

public class BuildingClickHandler : MonoBehaviour, IPointerClickHandler
{
    public delegate void BuildingClicked(BuildingClickHandler building);
    public static event BuildingClicked OnBuildingClicked;

    public void OnPointerClick(PointerEventData eventData)
    {
        if (OnBuildingClicked != null)
        {
            OnBuildingClicked(this);
        }
    }

    public string buildingName;
}
#

Changing the PointerEventData to BaseData works

gray mural
#

When having a class, derived from the Editor class, do I have to wrap it with the UNITY_EDITOR conditional, or does Unity ignore it in the build automatically?

crude mortar
next quiver
#

i have a script that loops and instantiates an Enemy gameobject of type grenade. What would be the best way to keep track of grenade1, grenade2 and so forth?

lean sail
gray mural
boreal glacier
#

Why does Unity struggle to find any input when I use KeyCode

#

It always throws up the error about the keycode not being found, but the name is always blank when I type the correct keycode in the controls list s

knotty sun
#

Dont use strings

boreal glacier
knotty sun
#

"KeyCode.UpArrow" is not KeyCode.UpArrow

#

Use KeyCode

boreal glacier
#

ah alright

#

was wondering because strings worked fine before I wanted to use keycodes

knotty sun
#

yes, but not like that

boreal glacier
#

Also is KeypadEnter the same as the regular enter key? I dont see a non-keypad variant so not sure

crude mortar
# gray mural When not willing to put it there, do I wrap it?

it couldn't exclude it by default because you can put multiple classes into one file, and you have to include the UnityEditor namespace to use the Editor base class, which would break compilation. You would have to wrap it like you showed above, yes. Also, you could always use an assembly definition (asmdef) to control which code gets compiled to editor / runtime, but if you don't like separating things by folders then I will assume that is a no-go too

boreal glacier
#

nvm

strange spruce
#

im working on an rpg and I'm running into some idea conflicts when working on the player character. The different components of the player (PlayerSkills, PlayerInventory, PlayerStats, etc) usually need access to each other, but manually dragging in each component to another isn't going to scale well. How should I handle this? My first thought is a Player component that just contains references to the components, but feels a bit dirty. Should I just GetComponent whatever I need?

gray mural
#

Or do I still have to use the conditional?

#

I just don't like that my folder structure is going to collapse when putting all editor scripts into the Editor folder

boreal glacier
gray mural
crude mortar
boreal glacier
#

For stats Ive just been using scriptable objects

cosmic rain
cosmic rain
boreal glacier
#

Oh fuck me theres no more errors and the game crashes

#

This is gonna be a fun night

strange spruce
# cosmic rain If you need help brainstorming that, share some of these cases with us.

PlayerSkills is going to need access to PlayerStats to check skill requirements. Your Strength stat (in PlayerStats) sets the max carry weight for PlayerInventory . the specific skills are TBD atm, but I imagine there could easily be one that increases carry weight. Whenever you level you get a point that can either raise a stat or buy a skill, so whatever does the leveling up needs access to both PlayerStats and PlayerSkills.

cosmic rain
strange spruce
#

that sounds good

#

thanks!

wraith spear
#

Is there a way of checking whether the code is running in a Test Assembly? I would think something like
#if UNITY_EDIT_TEST #endif
Would exist, but I can't find anything like it online / in the official docs. Of course #if UNITY_EDITOR works, but I want the code to run when I play in the editor as well.

knotty sun
#

what do you mean by a Test Assembly? A development build?

wraith spear
knotty sun
wraith spear
#

It does work as intended when I make a build

knotty sun
#

your other option is to add your own define constraint into both Tests and normal Playmode

wraith spear
#

Hmmm just including a !UNITY_INCLUDE_TESTS constraint in my scripts assembly doesn't work, I'll look around for some tutorials on the issue

cosmic rain
strange spruce
#

awesome

#

thanks again

#

when would I call the ctor? OnValidate/Start?

torn kite
#

Hey can someone help me optimise my game

#

i get randomly 6k batches when looking in a certain area

strange spruce
#

also, why properties instead of public fields? to make the set private?

lean sail
strange spruce
#

true

#

actually, that's where I can call the ctors lmao.

  public Inventory {
    get {
      if (_inventory == null) {
        _inventory = new CharacterInventory(this);
      }
      return _inventory
    }
  }
lean sail
#

also looks like youre missing the type there

strange spruce
#

fair

#

also, it was just a quick mockup lol

hard estuary
# strange spruce also, why properties instead of public fields? to make the set private?

Mostly to hide the possibility of modifying fields from other scripts. But it also makes editing easier for the future. E.g. you can run some kind of OnChange method to a property, which would be executed every time the variable changes, or add some validation (like _health = Mathf.Clamp (value, 0, _maxHealth)). Without property, you would need to copy-paste the code in every place you modify this variable. But probably in 80-99% cases fields will be more than enough.

prime acorn
#

what does FixedUpdate do when my game only runs at 45fps? Does it run 45x/sec? Does it change FixedDeltaTime?

wraith spear
queen saffron
#

Hi i need assistance in an issue ๐Ÿ™‚
I'm creating an object in runtime via ProBuilder Plugin. unfortunately, it doesn't assign the values as it should be. how to fix that?
vertices nor faces are being assigned that i can use later on for extrusion

cosmic rain
queen saffron
cosmic rain
tawny elkBOT
queen saffron
#

I've List of vectors 3d preprocessing that would define this polygon as it's positions. while faces are inserted as triangles that processing within the function CreatePolygon in a class Polygon . via ProBuilderMesh component i added them there and created the object by assigning values.
i debugged the code and the do really assign to positions and faces variables of the component. yet, i get withdraw them back from component after processing the mesh

#

Also, you can presume that activeGameObject is corretly stored in singleton class

#

Debugging of a simple 4 vertices example

cosmic rain
#

I think you're just accessing the wrong object

queen saffron
cosmic rain
#

Yeah, read my previous message.

#

That's a different gameobject

#

Not the one that you assign the vertices and faces to

queen saffron
#

ahh i see

#

thanks for the assistance @cosmic rain ๐Ÿ™๐Ÿป

molten sapphire
#

Hey, could someone help me with the scrollbar issue I'm getting? I'm changing the content size dynamically through script, and I want the scrollbar to change its size accordingly to the newly changed content size, yet it stays the same size

#

For reference my initial content size is like 5 pixels wide, and when it expands horizontally,I can scroll everything just fine, yet the scrollbar stays at the size as if the content size is still 5 pixels wide

thin hollow
#

After updating to Unity 2022 from Unity 2019, I now am getting errors in one of my scripts (which was found online and edited) that I used to determine the material the character stands on, to play appropriate footstep sound.
Now it gets this error on meshes:
Not allowed to access triangles/indices on mesh 'Wood_beam_thick_256' (isReadable is false; Read/Write must be enabled in import settings)

Is it possible to get the required data without enabling write on all the meshes in the game, as it sounds a bit unpredictably dangerous for the assets?
The code that generates the error:
https://gdl.space/adisonofex.cs

hard estuary
leaden solstice
thin hollow
thin hollow
thin hollow
#

Hm wait no it wouldn't, I think...

#

This looks more like it

leaden solstice
#

If so your material is i-th

thin hollow
meager tinsel
#

Alright. I've got a Dissolve Shader Graph that I've set up, and a float property that controls the amount the Shader actually runs on the given object. It's supposed to trigger ingame when you press the spacebar, but it isn't proccing, so I'm not really sure what's going on there.

public class DissolverScript : MonoBehaviour
{
    public float dissolveDuration = 2;
    public float dissolveStrength;

    public void StartDissolver()
    {
        StartCoroutine(dissolver());
    }

    public IEnumerator dissolver()
    {
        float elapsedTime = 0;

        Material dissolveMaterial = GetComponent<Renderer>().material;

        while (elapsedTime < dissolveDuration)
        {
            elapsedTime += Time.deltaTime;

            dissolveStrength = Mathf.Lerp(0, 1, elapsedTime / dissolveDuration);
            dissolveMaterial.SetFloat("_DissolveStrength", dissolveStrength);

            yield return null;
        }

    }

    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            StartDissolver();
        }
    }
}```
#

I just tried a Debug.Log on the last if statement to see if it was even getting the input, and it isn't, so I'm not sure what I'm missing, but that's probably it.

#

Just don't know how to fix it.

simple egret
# meager tinsel Just don't know how to fix it.

Take the log out of the if statement so it's ran unconditionally in Update. If you're still not getting it, then your script isn't active, it's on an object that is disabled, or is not attached at all to an object in the scene

thin hollow
meager tinsel
limpid siren
#

Hey guys, i am using unity cloud save
and i am trying to make the player to change his name (playerName)
i want to make a function that check if there is any other player with the name he is trying to change ( CheckAvailability(string name) )

Anyone know how to query in cloud save?

simple egret
# limpid siren

QueryAsync seems to take two arguments, but you're only providing one.

limpid siren
simple egret
#

Try things, can you construct an empty options with new QueryOptions()? Or maybe it has static members, like QueryOptions.Default? Use VS's completion list at your advantage here

limpid siren
#

in this example the queryAsync is only using 1 param

open bluff
limpid siren
leaden solstice
simple egret
limpid siren
#

Ye i am trying but it is like 1 out 100 possibilities to hit the correct usage ahah

#

but thnks anyways s2

#

ill keep trying ! ๐Ÿซก

meager tinsel
simple egret
meager tinsel
#

Yep, got it working now! Thank you.

simple egret
# limpid siren

Mmm I love unchecked parameters leading to "low-level" HTTP errors from the web server
Try passing null as the options? I've seen some examples online where they also use new QueryOptions() but with no apparent issues (or the forum thread don't mention them)

#

It's a shame that these docs are not kept up to date lol

crisp minnow
#

How to check if a specific component (InputSystemUIInputModule) is loaded somewhere in the game? Using RequireComponent is local to the game object only and of course ended up getting spammed with "multiple event systems present". I'd like to make this check once in the primary active scene manager, but would like it being able to check other scenes (event system would typically be present on a DDOL object, but if I'm running the scene in isolation, I'd want to create it myself as part of debug (will surround whatever logic with #if UNITY_EDITOR)

somber nacelle
#

you could use FindObjectByType

crisp minnow
#

That checks everything?

#
            var uiInputComponent = FindFirstObjectByType<InputSystemUIInputModule>();
            if (uiInputComponent == null)
            {
                
            }
somber nacelle
crisp minnow
#

That's perfect "This function is faster than Object.FindFirstObjectOfType if you don't need a specific object instance"

And I would just AddComponent if null, then?

somber nacelle
#

yep

crisp minnow
#

๐Ÿ™‡

somber nacelle
#

and since UnityEngine.Object has an implicit cast to null, you can just do if(!FindAnyObjectByType<whatever>()) AddComponent<whatever>(); instead of splitting the lines up if you don't need to actually access any of the stuff on the component

runic pawn
#

I have a Vector2 member that i set in my component's Update() called transformVelocity, and I print the value of that out to debug log... Now when I access that same member in my OnTriggerStay2D function it ends up being 0 instead of the value reported in the Update()... is there something about OnTriggerStay2D that would cause this?

#

here is the code in the Update()

#

and in the OnTriggerStay2D:

somber nacelle
#

use a bin site to share the whole class ๐Ÿ‘‡ !code

tawny elkBOT
runic pawn
#

and then the log just looks like this:

somber nacelle
#

and are you certain that these logs are coming from the same object? it's also pretty odd that you have exactly one log from update between each log from OnTriggerStay

runic pawn
#

it isn't always exactly one, i guess it just happened to be there for that clip

#

i mean usually it is, in the case that i'm looking at though

runic pawn
somber nacelle
#

how have you confirmed that

runic pawn
#

there is only one of these objects that moves

#

and it only logs, when it moves

somber nacelle
#

that doesn't mean the OnTriggerStay log is coming from that one

runic pawn
#

there is only one object that has an overlap as well

somber nacelle
#

include the name and instance id in your logs to be sure

runic pawn
#

ok

#

yeah, same thing

#

my screenshot utility just broke

#

but i put InstanceID in log and it shows it's the same instance for both prints

somber nacelle
#

ah wait, you only log the velocity when it does move. you need to log when it doesn't move too so you can see that it ends up at 0 before the OnTriggerStay tick

runic pawn
#

the thing is inside OnTriggerStay, the velocity is never non-zero

#

but i will try logging this all anyway

somber nacelle
leaden ice
# runic pawn

(transformVelocity.sqrMagnitude > 0.1f)
Debug.Log("tff:" + transformVelocity.sqrMagnitude);

#

You're only logging when it's greater than 0

somber nacelle
#

if you only ever specifically log it when it is non-zero you won't see when it is actually zero

runic pawn
#

yeah so idk why it goes to 0

#

it is never set any where else

somber nacelle
#

where in this several hundred lines do you actually move the object

leaden ice
#

If it's a Rigidbody

runic pawn
#

it is RB

leaden ice
#

Yeah so

#

Stop doing physics stuff in Update

#

That's your lesson for the day

#

Velocity needs to be measured in FixedUpdate

#

For that matter why not just grab it from the Rigidbody itself

runic pawn
#

ohh

#

i tried grabbing velocity from the RB and it's just 0, probably because position is set manually most of the time

#

i mean position is set based on input

#

there, finally working. thanks all

open bluff
leaden ice
open bluff
#

what should I do

leaden ice
#

The world up you actually want

devout cloak
#

Can someone help me solve a problem in my code? Itโ€™s a 2D movement code and there is something I canโ€™t figure out how to do.

open bluff
leaden ice
# open bluff

Yes, pick the one you want to be "up" for the aim constraint

devout cloak
#

I have a movement code that works well, but when I move left and right the sprite flips according to which direction. My sprite is a hook that hooks onto things so I donโ€™t want it to flip. Can someone please help me?

leaden ice
#

Probably not

#

Think about it

#

Or just try them out

open bluff
#

Actually, I tried them all, none of them changed the result, still the character's body becomes strange when turning.

somber nacelle
devout cloak
#

I used this code when I started. So itโ€™s copied from an old YouTube video, I have just been pasting it into my projects I need it in, so I have no idea what to do.

somber nacelle
#

and since you've not shared any code i have no idea what you need to change either

devout cloak
#

Should I send a picture of it?

somber nacelle
#

!code

tawny elkBOT
leaden ice
devout cloak
#

Can I just send a pic of the code so I can know the part I need to fix?

leaden ice
#

No, read the instructions on how to share code that have been shared with you

devout cloak
#

I only have discord on my phone, so I donโ€™t have the script on my phone itโ€™s on my computer

somber nacelle
#

discord is also a website

#

but even if we wanted to see pictures of the code, photographing your screen with your phone is an awful way to get those pictures

devout cloak
#

Screen shots

somber nacelle
#

just post the code correctly

devout cloak
#

Ok give me a few minutes

#

Ok so I put it in as a message?

#

With the back quotes

somber nacelle
#

if it is short, yes

devout cloak
#

How much is considered short?

somber nacelle
#

if you have to ask, then use a bin site

midnight brook
#

Just to check, does the * operator perform a dot multiplication?

somber nacelle
#

in what context

midnight brook
#

well, I'm trying to outputVector.x * currentSpeed a speed

#

where currentSpeed is some positive float

somber nacelle
#

that's just multiplying two floats.

midnight brook
#

"hmm" gets blocked; good job

somber nacelle
#

yes because it contributes nothing to the discussion

midnight brook
#

It's outputting a positive number even if I move left; some debugging confirmed as much

devout cloak
#

I can use those sites. Iโ€™m on my phone and it wonโ€™t let me save it

somber nacelle
somber nacelle
midnight brook
#

So I'm suspecting I'm inadvertently absolute-ing them

somber nacelle
#

well the multiplication operator is not doing that

devout cloak
#

I put the code into the site, and pressed the save button. Now what?

somber nacelle
#

share the link . . .

devout cloak
#

GDL.space/bomubimolu.cs

#

Sorry I didnโ€™t realize the link changed

spare island
#

did bro just manually type a link

somber nacelle
#

my guy, you have a method that you call "Flip". if you don't want the sprite to flip then consider just . . . not using that method

devout cloak
#

I donโ€™t know how to get rid of it. I tried and then the whole script didnโ€™t work

somber nacelle
#

how about you go actually learn what you are doing instead of blindly copying tutorial code without making an attempt to understand what it does

midnight brook
#

oh ffs I'm adding the vector to the currentSpeed

#

So both have the same damn sign, so ofc their product is always non-negative

devout cloak
spare island
#

sorry nobody like that here

somber nacelle
spare island
#

careful with latin u might get nerd emoji reactioned

#

(is it latin idfk)

midnight brook
#

yes

#

"to the person"

spare island
#

baited

devout cloak
#

Can someone tell me how to get rid of the flip variable

somber nacelle
#

there is no flip variable

midnight brook
#

...Find where you're flipping the sprite in the code, and then... remove it

#

It's not a difficult thing, if you know why you wrote the code that you did

spare island
#

there is a flip variable

somber nacelle
#

that's not in their code

#

i even already told them exactly what they need to do. but allegedly it makes the whole script stop working (it can't)

devout cloak
#

I get an error and I canโ€™t run the game

midnight brook
#

Well, if they're saying they copied code - which it feels like they didn't properly understand - then it's part of the script that causes the flip

lean sail
#

Sounds like someone copy pasted code without learning the basics

spare island
#

so did you look at the error and see what it says

#

its not just scary red text

somber nacelle
#

that sounds like too much effort for them

midnight brook
spare island
devout cloak
#

I got it. I deleted the whole bottom part last time instead of just the โ€œflip();โ€

#

Silly me!

spare island
#

what

midnight brook
#

what

somber nacelle
#

they deleted the Flip method without actually removing the call to that method from their Update method. now that they've actually followed my instructions by removing that method call it works as intended

lean sail
#

And plus if you're gonna try insulting people who helped u, u likely arent gonna get future help in here

#

So gotta learn the basics either way

limpid siren
somber nacelle
#

the error message is pretty clear, you have not supplied the second parameter that the method expects

limpid siren
somber nacelle
#

did you look at the docs for that QueryOptions type?

somber nacelle
limpid siren
blazing dragon
#

how could i make doors work for a top down game

#

i got this so far a top layer for the walls of the house and a bottom layer for ground

#

but how could i make doors, cant do it on the tilemap right?

spare island
blazing dragon
spare island
blazing dragon
#

thanks a lot

spare island
lament island
#

Anyone able to help with the following question? I'm trying to obtain a method using reflection but that method was sealed somewhere in inheritance. The method obviously still gets called on the base class and I need to invoke the method and have it make calls to deriving methods further down the inheritance line. Is it possible to do such a thing and if so, how would I do it?

dense sparrow
#

i'm attempting to make a model importer, and I have most of it completed. however, i'm having some difficulties processing the armature information. i'm unsure how I should generate bindposes

leaden ice
lament island
lament island
# leaden ice If it's sealed there's no such thing as a deriving method for it

I have a method DrawPropertyGUI() which I seal in a class. The class calls a lower down method DrawPropertyGUIWithEvents() which is designed to be the base functionality of DrawPropertyGUI() of the from that point forward. The base class simply calls the overridable method for its functionality along with some housekeeping for the base class. I need to invoke the base functionality of DrawPropertyGUI() externally via reflection and invoke it to draw properties and do housekeeping tasks

spring creek
lament island
#

I'm making a generic class selector and want to implement the drawing of custom property drawers inside of the class selector

#

Right now I invoke the DrawPropertyGUI() method from the custom property drawer in order to do this.

lament island
leaden ice
#

Not sure what the issue exactly is

#

are you saying you want to call DrawPropertyGUI without calling DrawPropertyGUIWithEvents()?

#

If so, that's beyond the limits of what reflection in C# can do for you. it cannot rewrite already written functions.

#

If you want that to happen, you need to separate the functionality you want into a separate method that doesn't call DrawPropertyGUIWithEvents(), and call that directly.

lament island
leaden ice
#

so it's not actually calling a derived version, it's calling the virtual or abstract method, which gets resolved only at runtime

#

anyway it's beside the point

lament island
leaden ice
#

Is this what you want?

#

For example, you have something like this:

abstract void DrawPropertyGUIWithEvents();

sealed void DrawPropertyGUI() {
  DoSomething();
  DrawPropertyGUIWithEvents();
}``` and you want to do only `DoSomething();` and not `DrawPropertyGUIWithEvents();`?
lament island
#

I want to execute the DrawPropertyGUI for the base class

leaden ice
#

again, what does that mean?

#

Because DrawPropertyGUI for the base class includes calling DrawPropertyGUIWithEvents() as far as I understand

#

please correct me if I'm wrong there

#

See my example just above for what I think you mean

lament island
#
            object customDrawerInstance = Activator.CreateInstance(customPropertyDrawerForType);
            FieldInfo fieldInfo = property.GetFieldInfoAndStaticType(out Type t);
            customPropertyDrawerForType.GetField("m_FieldInfo", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).SetValue(customDrawerInstance, fieldInfo);
            objectPropertiesContainer.Add((VisualElement)customPropertyDrawerForType.GetMethod("CreatePropertyGUI").Invoke(customDrawerInstance, new object[] { property }));

So here's whats happening right now

leaden ice
#

that's not an explanation of what's happening right now

#

This is your code right now, which will very successfully call CreatePropertyGUI

#

in which case, you have achieved your goal

#

So I'm trying to understand how your goal differs from just calling CreatePropertyGUI

#

(you said DrawPropertyGUI above and this code says CreatePropertyGUI so i'm not sure which is right now)

#

I feel like I asked some pretty simple questions above

#

If you answer them, it will clear up a lot.

leaden ice
#

ok so... again, your intention is to try to only call part of that function?

lament island
#

No

#

I just need the base function

#

so that should work?

leaden ice
#

there is no "base function"

#

it's sealed

#

there's only one function

#

you said it was sealed

#

therefore there are no derived functions

lament island
leaden ice
#

right so then what you want is not possible

#

What you need to do instead is just call DoSomething(); via reflection. Not DrawPropertyGUI()

#

(per my example)

lament island
#

I could, but the issue with that is that I wouldn't know the name of the function I'm trying to call if I want to make this generically function for all property drawers

leaden ice
#

If you are making it "generically function for all property drawers" how could you possibly know what their CreatePropertyGUI functions contain?

#

Maybe you could back up and explain what you're actually trying to achieve here

lament island
#

It will always contain instruction to draw the UI toolkit GUI

leaden ice
#

you're asking an XY problem

leaden ice
#

you're asking some very specific question about your attempted solution which for some reason involves reflection

#

but you haven't explained what you're actually trying to do

lament island
# leaden ice but you haven't explained what you're actually trying to do

The following code attempts to draw the properties in the inspector for a selected type via a dropdown. I currently take in info for an attribute, find all deriving types via reflection in a dropdown menu and let the user select one. Once the user selects a class, I want the drawer to display the drawer found for the type inside the property drawer. If one doesn't exist, it just defaults to drawing all the field for the type

#

this is why my code is heavily utilizing reflection

modest brook
#

hey guys, how can i make an object lock to the cursor? i wanna make a flashlight stick to the cursor the whole time
i have a custom cursor as well currently and a cursor manager and this is the code i have:

`void Start()
{
cursorHotspot = new Vector2(cursorTexture.width / 2, cursorTexture.height / 2);
Cursor.SetCursor(cursorTexture, cursorHotspot, CursorMode.Auto);

flash.transform.position = 

}`

spare island
#

i dont really understand what this error is even saying

#

what does it mean 'extra field'

#

there's only one

cosmic rain
spare island
#

!code

tawny elkBOT
spare island
#

there's no compilation errors, only build errors

cosmic rain
#

Also, do you have some assemblies that are only compiled for the target platform?

spare island
#

i restarted and it decides my code is fine now shrug

#

i tried forcing a recompile too and that didn't work

runic pawn
#

is it me or does Physics2D.Raycast function only work if you pass in a single layer mask, it doesnt work with combined layermasks?

#

is that to be expected ?

cosmic rain
runic pawn
#

i'm passing in an int in both cases so i don't think its the wrong overload

cosmic rain
runic pawn
#

well it doesnt hit Stage, thats for sure

cosmic rain
#

Then debug what it does hit.

#

Perhaps there's an object on the bomb layer that is hit first.

runic pawn
#

it doesnt hit anything as of now, i just never checked it against Bomb

cosmic rain
#

Wdym?

#

The issue is with the commented code right?

runic pawn
#

right

cosmic rain
#

And when you uncomment it and log what the raycast hits, what does it show?

runic pawn
#

the commented code makes it miss all hits with Stage

cosmic rain
#

A raycast would only hit the first thing in it's way.

#

If there is an object on the Bomb layer in front, it would only hit that.

runic pawn
#

sec i might see the issue

#

can i have it get multiple hits using layermasks?

cosmic rain
lean sail
cinder pine
#

Hello,
I'm currently working on the implementation of the new Input System and I wondered if it was possible to wait for an input in a coroutine?
Here's the code

protected IEnumerator WriteText(string input, Text textHolder, Color textColor, Font textFont, float delay, AudioClip sound, float delayBetweenLine)
{
    textHolder.color = textColor;
    textHolder.font = textFont;

    StartCoroutine(MakeSkippable());

    for (int i = 0; i < input.Length; i++)
    {
        textHolder.text += input[i];
        if (input[i].ToString() != " ")
        {
            SoundManager.Instance.PlaySound(sound, "Sound");
        }

        yield return new WaitForSeconds(delay);
    }

    yield return new WaitUntil(() => OnSkipDialogue());
    Finished = true;
}

The errors:

  • CS1662 Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
  • CS0029 Cannot implicitly convert type 'void' to 'bool'
    Could you help me please?
#

The OnSkipDialogue function is called when the player presses Enter (keyboard) or Cancel (controller)

lean sail
#

You could just store a bool and set it to true in OnSkipDialogue

tawdry pecan
#

I have an system where players can pick up dropped weapons by pressing F. But when the player picks it up, the weapon doesn't go to the hands transform but rather above their head. The weapon is still a child of the hands transform upon pickup. The hands transform works indicated by the rocket launcher. The pistol and the knife doesn't apply

Here's all the code associated:
https://hastebin.com/share/ihubihihal.csharp

storm wolf
#

Anyone have any decent tutorials/advice on async/task stuff? I have a saving animation and I want the data to save asyncronously so it doesnt interrupt the animation, not sure where to start. Found some forums but nothing really useable. Thanks! (never touched this stuff before now, this seems like a simple enough problem to get started on)

edit: also I do already have a save/load system I just want to make it async somehow or write a method that asyncly calls my existing save function and waits for it to be done

cosmic rain
storm wolf
#

I can? Currently I am yielding until the save is done and then continuing but it interrupts the animation

cosmic rain
#

Or just some checks in update

cosmic rain
storm wolf
#

no it is a play on awake function that just moves something across the screen

#

no code attached

cosmic rain
#

"play on awake function"? So it is a code driven animation?

storm wolf
#

and my save coroutine is literally just this (as pseudocode):

yield waituntil save

yield return startcoroutine(fade screen function)

load next scene

cosmic rain
#

Well, That is "async" technically.

storm wolf
cosmic rain
#

If your save is taking a lot of time and is executed on the main thread, there would be a stall obviously

storm wolf
#

that stall is unavoidable?

cosmic rain
#

It is avoidable. But async is not gonna help with it. At least not the way it's normally used in unity.

storm wolf
#

hmm okay what would you suggest?

cosmic rain
#

Use the profiler to see if it's actually a stall

storm wolf
#

okay one sec

#

how would I be able to tell if its a stall?

#

for some reason the times are missing but

#

its 260ms but im missing details?

lean sail
#

can u not expand that to show more?

cosmic rain
storm wolf
#

yes

storm wolf
cosmic rain
storm wolf
#

oh.

#

lol.

lean sail
#

you can also make the column smaller by dragging the while line near Total to the left

cosmic rain
storm wolf
#

what do you mean? the SaveGame ?

cosmic rain
#

What does that yield instruction do?

#

Yes

#

Can you share the code?

storm wolf
#

yeah one sec

#

thats the name of my class so

#

its not an instruction

#

yield return new WaitUntil(SaveSystem.SaveData);

#

thats probably the line its worried about

cosmic rain
#

Yes

#

What's SaveSystem.SaveData?

storm wolf
#

just encrypts and saves the data

#

the encrypting is what is taking a while ill save you that effort

#

I can send it if youd like though

cosmic rain
#

Send it.
But if what you're saying is correct, then it's this encryption that you'll need to async or on a background thread.

storm wolf
#
    static string Encrypt(string plaintext, string password)
    {
        byte[] salt = Encoding.UTF8.GetBytes(password);
        byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
        byte[] key = GenerateKey(password, salt);
        byte[] iv = GenerateIV(password, salt);


        using (Aes encryptor = Aes.Create())
        {
            encryptor.Key = key;
            encryptor.IV = iv;
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(plaintextBytes, 0, plaintextBytes.Length);
                }
                return Convert.ToBase64String(ms.ToArray());
            }
        }
    }
cosmic rain
#

If it's many small operations, you can make it async on the main thread.
If it's one big operation, there's not much you can do aside from running it on a background thread.

storm wolf
#

so should I make my save function async then so that I can await the encryption

#

is that like a standard approach

cosmic rain
#

Share the SaveSystem.SaveData code

storm wolf
#
    public static bool SaveData()
    {
        try
        {
            FileStream stream;
            if (File.Exists(path))
            {
                stream = new(path, FileMode.Open);
            }
            else
            {
                stream = new(path, FileMode.Create);
            }
            BinaryWriter writer = new BinaryWriter(stream);
            PlayerData data = new();
            string textData = JsonUtility.ToJson(data);
            string pk2 = $"{GetCode1()}-{GetCode2()}";

            string encryptedData = Encrypt(textData, pk2);

            writer.Write(encryptedData);
            writer.Dispose();
        }
        catch (Exception)
        {
            return false;
        }
        return true;
    }
cosmic rain
storm wolf
#

profiler markers?

#

you mean like debug so it stops it?

storm wolf
#

ah okay i have not used these before

#
    static readonly ProfilerMarker s_PreparePerfMarker = new ProfilerMarker("SaveSystem.Save");
    public static bool SaveData()
    {
        try
        {
            s_PreparePerfMarker.Begin();
            FileStream stream;
            if (File.Exists(path))
            {
                stream = new(path, FileMode.Open);
            }
            else
            {
                stream = new(path, FileMode.Create);
            }
            BinaryWriter writer = new BinaryWriter(stream);
            PlayerData data = new();
            string textData = JsonUtility.ToJson(data);
            string pk2 = $"{GetProcessorID()}-{GetMotherboardSerialNumber()}";

            string encryptedData = Encrypt(textData, pk2);

            writer.Write(encryptedData);
            writer.Dispose();
            s_PreparePerfMarker.End();
        }
        catch (Exception)
        {
            return false;
        }
        return true;
    }

am I way off

cosmic rain
#

I think one of the main issues here is that you're executing the whole save logic on the yield instruction. That's definitely gonna botcher unities coroutine execution quite a bit. You should just be checking a simple bool instead. Something like: SaveSystem.SaveComplete.

cosmic rain
#

Aah

#

Okay, that's fine.

#

And place another one in encrypt

storm wolf
storm wolf
#

is that not the same effect as waiting for the save to finish

#

or you are saying that yielding the method is screwing the coroutine

lean sail
#

is there a reason also you're converting to json, encrypting, then writing as binary? because binary isnt human readable anyways

cosmic rain
cosmic rain
#

If it was a simple bool check, unity would check for it real quick and continue executing it's player loop. While currently it has to wait for it.

storm wolf
lean sail
storm wolf
#

They don't have the password

#

unless they do some deep digging

cosmic rain
storm wolf
#

looks like it is the encrypt

storm wolf
cosmic rain
chilly surge
#

The entire SaveData method is executed synchronously.

#

Putting it in a coroutine doesn't magically make something asynchronous.

cosmic rain
# storm wolf What do you mean by this 2nd sentence

Wait until is called by unity every frame to see if the coroutine can be resumed. If it returns true, it resumes the coroutine, otherwise checks again on the next frame.

What you have now is that it executes the save method entirely instead of checking a variable. This would mean that unity can't move on to executing other code until the save method returns.

Obviously that's only part of the problem, but it's still something you should consider refactoring.

storm wolf
#

ok I'll turn that into a bool now, and then should there also be internal async methods in the save system

cosmic rain
#

You can create the arrays and other data structures on game start in your SaveGame class. Then reuse these arrays instead of creating and destroying new ones on each save.

lean sail
#

I'd truly just get rid of the encryption and move on if it works as fast as you want. Though not sure how much of a "encryption wont matter locally" talk I wanna go through

cosmic rain
storm wolf
cosmic rain
#

You can have a static constructor or some kind of initialization function where you do that

chilly surge
#

Idk if JsonUtility or your PlayerData is thread safe or not, but you can just do that part on the main thread and move everything else to a different thread and that will be all.

#

Don't need to change much else.

lean sail
# storm wolf if they get the password they deserve it lol

Same could be said about anyone who actually decides to convert from binary to json, and then back. Trust me when I say if the password is local then they already have it. Itll just be a minor headache for the person who writes an app to modify save files if your game gets popular enough

storm wolf
#

yeah but i would rather it be a mediocre headache than a minor one, binary is way too easy I would rather encode and encrypt

chilly surge
#

If it's a single player game, who cares if the player is cheating; if it's a multiplayer game, you can't protect it this way regardless.

cosmic rain
chilly surge
#

I doubt GC kicks in in that exact profiler frame to be the issue.

#

Not sure how saving is used in their game, but usually allocation is only a big concern in reoccurring operations, so things that are called every frame or every fixed amount of time, if GC can't keep up with your allocation then it has no choice but to pause the world to do clean up. In one off operations, allocation is generally fine, and presumably saving isn't performed all the time.

storm wolf
#

ok I improved it, visibly less buffer, still a tiny kick though

#

    static string _password = null;
    static byte[] key = null;
    static byte[] iv = null;
    static byte[] salt = null;
    static void Init()
    {
        _password = $"{Code()}-{Code1()}";
        salt = Encoding.UTF8.GetBytes(_password);
        key = GenerateKey(_password, salt);
        iv = GenerateIV(_password, salt);
    }

this is whats left of the save function:


    public static bool SaveData()
    {
        try
        {
            SaveComplete = false;
            FileStream stream;
            if (File.Exists(path))
            {
                stream = new(path, FileMode.Open);
            }
            else
            {
                stream = new(path, FileMode.Create);
            }
            BinaryWriter writer = new BinaryWriter(stream);

            PlayerData data = new();
            string textData = JsonUtility.ToJson(data);
            string encryptedData = Encrypt(textData);


            writer.Write(encryptedData);
            writer.Dispose();
            SaveComplete = true;
        }
        catch (Exception)
        {
            return false;
        }
        return true;
    }

#

SaveSystem.Init();

SaveSystem.SaveData();

yield return new WaitUntil(() => SaveSystem.SaveComplete);

not sure if this is what you meant?

lean sail
storm wolf
#

how do you mean

lean sail
full canopy
#
using System.Collections.Generic;
using UnityEngine;

public class LinkedComponent : MonoBehaviour
{
    [SerializeField] private string comment;
    [SerializeField] Component linkedComponent;
    [HideInInspector] public Component link
    {
        set => linkedComponent = value;
        get => linkedComponent is LinkedComponent ? linkedComponent.link : linkedComponent;
    }
}```
compilation error: ```'Component' does not contain a definition for 'link' and no accessible extension method 'link' accepting a first argument of type 'Component' could be found (are you missing a using directive or an assembly reference?)```
how would I get link to return linkedcomponents link if the linked component is a linked component?
(i hope that made sense)
i could obviously just getcomponent, but if there's multiple how do i ensure that its the correct one?
storm wolf
spring basin
#

Hey, Im trying to add ads to my UWP unity game. I came across this provider called AdsJumbo. But they seem to have only native cpp support. So how do I call methods like ShowInterstitial and ShowReward from within the unity C# script to the external native code?

lean sail
storm wolf
#

:/ is that the only option or would using a Coroutine work here

lean sail
cosmic rain
lean sail
full canopy
storm wolf
#

this sucks

cosmic rain
storm wolf
#

OHW AIT

#

ur right lmaooo

#

im so stupid

west lotus
#

Putting the entire encryption process on a background thread would be rather easy. I do not think that the encryption algo itself is parallizable.

#

Why does your init generate 6mb of garbage ?

cosmic rain
#

Well, from what we can see, the save itself, including the encryption is just 3 ms. The issues was the GC.

lean sail
#

it does seem like a lot, especially since encryption is made to be quick. It could also be from that _password thing which is 2 method calls and string interpolation

cosmic rain
#

Yeah, Code() and Code1() are sus as well.

storm wolf
#

moving the init nulled it out or at least like 95% of it but I can't notice it and the editorloop takes longer than the save now so thats a win

storm wolf
#

Thank you @cosmic rain and @lean sail for the help appreciate it seriously +1 rep for you both

hidden flicker
#

I'm so fucking confused