#archived-code-general

1 messages · Page 157 of 1

silk cairn
#

ah ty

cobalt gyro
#

is key remapping doable without the new input system

lapis egret
#

If I want to pre-calculate the effect that manipulation of a parent object will have upon its child object, how would I do so?

rain minnow
fleet shell
#

Is there a way to hook a debugger onto Unity so I can get a stack trace of my code executing when I hit generate for my procedural terrain? Every time I generate a 100x100 terrain, it takes 15-20 seconds just to execute, and I wanna see what's taking so long as when it comes to the final game the map is going to have a 1kx1k map, which when I tried generating took 30 mins.

I hooked VS into Unity using debugging and also using the Unity profiler, but can't see anywhere the info that I need to see how long each process is taking

rain minnow
fleet shell
lean sail
fleet shell
#

Yeah, I think the issue is with my noise map generator, as it has a lto of calculatiobs it has to do, which means I am probably gonna have to chunk it up and hope that it works out. Though I am still curious as to what process is actually taking the longest

lean sail
cosmic rain
fleet shell
rain minnow
#

now switch the Timeline to Raw Hierarchy . . .

cosmic rain
fleet shell
#

That's my calculateNormals AE_Sweat

mossy snow
#

I like the part where you copy the entire triangle buffer, get a single int out of it, and then throw it into the garbage ... 3 times, per triangle

cosmic rain
#

Getting triangles from the mesh buffer is pretty heavy. You might want to get and set them once instead of doing it separately for each triangle.

leaden solstice
#

I’d blame Unity for bad API

fleet shell
cosmic rain
fleet shell
#

Alright, here's to hoping that clears up some of it at least

leaden solstice
#

You can use GetTriangles with pre made List to avoid allocation

mighty yew
#

I'm trying to make an inventory, but I'm having a little trouble. I thought about making a parent class and having a bunch of children inherit from that parent, that way I can create a list of "items" but I'm not sure if thats the best way to go about it. Any tips?

urban orbit
mighty yew
#

make the blocks always check to see if they're at a "good" location, and if not, move them towards the closest good location

urban orbit
#

but how do I make the touch drag movement?

mighty yew
#

what do you mean by touch drag movement?

urban orbit
#

individual drag movement with touch input for each block like in the game

mighty yew
#

Oh i'm not a mobile developer so i'm not really sure how the inputs for touch screens work, sorry.

urban orbit
#

it's okay

unique cloak
#

If a gameobject with a script attached is destroyed using Destroy(this.gameObject);, and the attached script has some code in the Monobehaviour Update() method, is there any chance that the script might run the update method after the gameobject is destroyed? Or more generally does the script keep executing after the gameobject it's attached to is destroyed?

cosmic rain
unique cloak
light rock
#

yes

fathom geode
#

I'm struggling with some seemingly simple math and was hoping someone could point me in the right direction
I've got values X and Y that always need to be 0.1 apart, relative to percent Z (from 0 to 1)

ie, if Z = 0, x = 0, Y = 0.1,
if Z = 1, X = 0.9, Y = 1.
Where I get confused is how to express this linearly, so Z can go from 0 to 1 without clamping on either end

lean sail
unique cloak
#

Cheers

unique cloak
lean sail
unique cloak
#

Nevermind ignore me

#

Im just confused haha

#

@fathom geode you mind me asking what the math is for?

#

Seems like an odd calculation

fathom geode
#

Extruding a spline based on percent, length needs to stay constant

lean sail
#

i was imagining its some start/end point, like a scrollbar

unique cloak
#

oo cool

lean sail
fervent jacinth
#

how do i make a cube go between theese two points like a line renderer?

#

i already have the two points as vectors

west path
ashen yoke
#

or * 0.5

fervent jacinth
#

how do i turn that into a rotation

#

quaternion euler?

ashen yoke
#

what you turn into rotation?

fervent jacinth
#

i already have the scale of the cube working using the distance between the points, but how do i angle it so its in between them

ashen yoke
#

i dont understand

#

you keep piling up more and more things in your question

#

scale, angle

#

draw another picture with what you actually want

fervent jacinth
#

heres a really bad drawing

#

like you would use a line renderer

#

so the front of the rectangle is on one point and the back is on the second point

ashen yoke
#

you want to stretch a box along a line?

#

transform.forward = B - A

fervent jacinth
#

thanks so much, i made that way more complex then it had to be 🤣

cobalt gyro
#

🗿 sans = transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform;

ashen yoke
#

just save before it

#

or better dont do it

dense estuary
#

Did you ever find a solution?

#

because if not I might see if I can animate the camera my self, but I'm not sure if that'll work.

ocean oasis
#

I've got a weird one. I wanted to make some simple soft body stuff, so I followed a tutorial and it's perfect. But now I wanted a script to make it grow with time. For whatever reason, when growing, the soft body springs just totally let go and pretend like they dont exist. Video link for the soft bodies: https://www.youtube.com/watch?v=W3x143cYF88&start=197

Soft Body 2D Tutorial Jelly Effect - Unity (Easy)

Tutorial from Binary Lunar: https://youtu.be/H4MTeKT0QFY

Music used in this video

Boogie My Woogie no copyright Piano Boogie, royalty free 1940s Swing
royalty free Music by Giorgio Di Campo for FreeSound Musi...

▶ Play video
patent quiver
#

Hello I'm currently working on a player selection system to allow players to view each other's names and stat values(HP/MP). I'm trying to use raycasting to detect player tag, but this only works properly for the client that is running the server.(which doesn't quite make sense to me..) For other clients, the detection field is way off the player model but is somewhat constant, it's as if there's an invisible box above the player model that can't be adjusted. I'm using Fishnet for networking.

Here's part of the relevant code.

    {
        if (Input.GetKeyDown(KeyCode.Tab))
        {
            DeselectPlayer();
        }
        
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            if (hit.transform.CompareTag("Player"))
            {
                NetworkBehaviour clickedPlayer = hit.transform.GetComponent<NetworkBehaviour>();
                isHover = true;
                if (clickedPlayer != null && clickedPlayer != this && Input.GetKey(KeyCode.Mouse0))
                {
                    SelectPlayer(clickedPlayer);
                }
            }
            else
                isHover = false;
        }


        if (selectedPlayer != null)
        {
            UpdatePlayerInfo();
        }
    }

    public void SelectPlayer(NetworkBehaviour player)
    {
        if (selectedPlayer == player)
            return;

        selectedPlayer = player;
        UpdatePlayerInfo();
    }```
mossy valley
#

Any idea or resource that could help me with making a Daily Quest system

lean sail
elder flax
#

How would I use Astar pathfinding to kind of see if a cell is connected to another cell in a group of hexagon cells?

#

to clarify each 2d cell is a different object (with colliders and disabled rigidbody) and when a cell gets destroyed (killed) then i want to check all the cells and see if they are connected by another cell, if not the rigidbody should be enabled and it would float away

#

or is there some other algorithm/way to do it

mellow sigil
#

That's not really a job for A* (or any pathfinding algorithm.) You already need to know connections before you can do pathfinding. You just need to check all adjacent coordinates, if none of them has a cell in them then it's not connected to anything

elder flax
#

yeah but the issue there is that cells could be connected to more cells so like

#

if you break a support an entire section could disconnect right

mellow sigil
#

ok well a group of cells is different from "a cell"

elder flax
#

oh yeah i didnt really mention that did i oops

mellow sigil
#

You could try a flood fill algorithm, if it doesn't fill everything then there's a disconnected section

elder flax
#

good idea

patent quiver
ashen yoke
#

as references

elder flax
#

no

#

the 'swarm' controller on the parent stores all of its cells

#

ive just implemented a flood fill algorithm to search for disconnected cells that I can just call whenever a cell is destroyed

quartz folio
river wigeon
#

So I've made a state machine to handle game logic. Currently I'm not using any inheritance, and I'm instead trying to handle state specific entry and exit behaviour by calling functions in other objects. The problem I've found however is that this doesn't offer enough control, and instead I'm basically having to write the same code I would have done if using inheritance but instead it's in scattered in different places which is definitely worse. Any advice? I'm currently planning on just switching to inheritance

sturdy pagoda
#

thank you for actually writing the code my guy

#

it works perfectly now

steady moat
sturdy pagoda
#

oh well in that case id actually want to redact my thank you

#

im jk

sharp acorn
#

How could i go about copying images from window's clipboard?

steady moat
sharp acorn
#

I found that if I put the System.Windows.Forms.dll file in the project folder, Unity does the rest, but I cant find the .dll xD

craggy veldt
#

why you want winforms in Unity 😭

#

winapi is your best bet here

night storm
#

is it bad for performance to have a coroutine permanently running this?

IEnumerator MyCoroutine() {
while (true)
  if (myQueue.Count > 0) {
    // things here
  }
  yield return null;
}

it checks if a queue has items in it each frame and idk if that is bad

wind palm
#

Do you need it every frame, also, why bother with a coroutine?

livid sandal
#

Hello i have several question regarding collider2d i'm not sure if this is the right place to ask but here it is

1.) I Have 2 boxCollider2D 1 in MidevalKnights and 1 in Weapon ( as in the image )
2.) however i only have rigidbody on the MedievalKnights

Expected:

  • when collider in the Weapon is hitting an enemy "Weapon is hitting an enemy" i damage them

Problem:

  • When my player boxCollider hit an enemy it is also count as weapon hit which is not expected, how do i differentiate between these 2 colliders? Thanks in advance
night storm
ashen yoke
wind palm
ashen yoke
#

you are trying to solve something that is typically solved with events/observer pattern

livid sandal
#

i am using delegate events on the WeaponHandler so the trigger is not actually in the MedievalKnights itself

night storm
livid sandal
#

so how do i properly handle these kinda thing?

wind palm
ashen yoke
#

i guess player deals damage

#

then you need to relay events to the root for processing

livid sandal
#

ouwwh that make sense but i also wanted my player collider colide with the enemy

#

currently i dont set include layers to anything in both of the collider

livid sandal
ashen yoke
#

this is what i do

livid sandal
#

maybe i should make the trigger and the calculation in the enemy instead? :/

#

i have been stuck here since yesterday XD

ashen yoke
#

set of interfaces ICollisionEnterHandlerRelay etc
implemented on root

#

on the colliders are components CollisionRelay

#

they have field target, of type monobehaviour

#

when they receive a collision event from unity they cast the target to the interface, if cast is valid, the method is called

livid sandal
#

im really sorry i'm new to unity so i have might not understand what you are talking about XD

ashen yoke
#

ok, what should i explain

#

or i can simplify the approach

#

simply have public void OnCollisionFromRelay(Collision col) on your root player controller

livid sandal
#

private void OnTriggerEnter2D(Collider2D other)
{
if (onHittingTarget != null) onHittingTarget(other);
}

Basically i wanted to know what collider is hitting with the "other" collider

ashen yoke
#

so the code on your colliders/triggers becomes

#
private void OnTriggerEnter2D(Collider2D other)
    {
        _medievalKnight.OnTriggerEnter2DRelayed(this, other);
    }
livid sandal
#

ohhhhh rightttt we HAVE THISSS

#

this

#

right let me try

#

XD

#

oke this works

#

i dont know if this gonna be costly or not tho

ashen yoke
#

no

pure cliff
#

You should have a "PlayerVulnerable" layer which contains hitboxes for stuff that hurts player (enemies, ebemy abilities, enviro), and the players "vulnerable" hitbox.

Then "EnemyVulnerable" layer which has the enemies body hitboxes, and the players attacks or whatever and any other stuff that can hurt enemies

#

Theoretically also a "neutral vulnerable" layer if needed, if you need effects that hurt both players and enemies (like bombs or whatever on your game)

#

This let's you have stuff like enemies that have "non vulnerable" portions of their hitbox.

wise arch
#

Looking for code review / feedback

This is for a tetris inventory, like the one in tarkov

https://paste.ofcode.org/5C5W79U86uygVc6ytPPVG7

I am highly aware that my code is very bad, this is my first iteration to get it working, I am looking for feedback so that I can structure it better.

lucid matrix
#

Hey, can you tell me how to import GLB file using GLB importer? I know how to do it from link but I need to load from project already downloaded glb file and create custom avatar from that

crystal dagger
#

Heya

#

I have a body and head separated

#

But when i try to apply transform effects to it, nothing happens

#

Only general transforms applied to "kkkxd" work.

sleek bough
#

Is this a code question?

crystal dagger
#

well quite

#

I'd like to know if there is a way to move it still being a child

#

maybe an option that i can mark i don't know

#

I tried looking for this everywhere in the manuals and google and etc

sleek bough
crystal dagger
#

so you mean i can fix that through blender normally?

sleek bough
#

Probably. I'm not that familiar with modelling. You should ask in appropriate channel for that

crystal dagger
#

Well, it's working fine on blender and animations. The real problem is that the transform does not apply to it. I think it's working just fine as a model

mighty yew
#

I'm trying to make an inventory, but I'm having a little trouble. I thought about making a parent class and having a bunch of children inherit from that parent, that way I can create a list of "items" but I'm not sure if thats the best way to go about it, because ill have like 100 or so files at the end of development that are just items. Any tips?

crude mortar
#

Your only other option is making items get constructed completely via the inspector using a very data oriented approach (or in code as functions). It would be one item class that has all the necessary information to construct any item type you want. A health potion would be a Usable and it would perform a Health modification when used, for example.

I think this approach is hard to design for and you are probably better off having a different script for each item if you want specific functionality. It is easier to understand and refactor as long as you don't make huge hierachy chains (like Item -> Weapon -> RangedWeapon -> Bow -> MyBow)

steady moat
placid obsidian
#

Hiya, probably a weird question -

I want to take a gameobject(green thing) and move it based on the hitpoint of a raycast towards the red square ive drawn, how would i go about getting the direction and coords to transform it? hmjj

floral onyx
#

Hello Sir, I'm trying to do a fuzzy sugeno method here, so I'm applying the method to the enemy, here is the link of the full code:

https://paste.ofcode.org/SfgSLQqLrMmBgqw3CD5A3b

The core code is in the function of EnemyAttack(). The output is NaN, what is seems to be the problem?

mighty yew
crude mortar
#

yeah, so it may not be worth making it extremely modular if you know that most things will be very unique in function

leaden ice
#

find where the NaN starts
usually it'd be from divide by zero somewhere.

crude mortar
#

modularity is harder to setup and provides benefits later, but if you never get to that "later" (in terms of reusing stuff) then it's pointless

mighty yew
#

alright, so one parent class is the way to go? is there a way to have multiple children per file cause honestly im just dreading creating dozens of files with like 9 lines of code in them each lol

crude mortar
#

don't dread that

#

more code on the screen does not mean that the code is somehow better or more reusable

#

I usually try to go for exactly what you are dreading—many small files. If you don't need much code to make things work, you are probably doing something right

floral onyx
crude mortar
#

I think as long as they aren't a Unity object

floral onyx
crude mortar
floral onyx
leaden ice
#

find where you're dividing by zero

#

and stop doing that

crude mortar
mighty yew
#

but there won't be like, an issue with making a hundred files from a storage/speed perspective? i feel like that many files might lag the project?

crude mortar
#

I mean it's really the amount of code that matters

#

which you can't get around

mighty yew
#

alright i guess, thats fair

crude mortar
#

just my generic library of stuff I like to have in every project is hundreds of files, and that's before I even start the project

#

it is not that much slower than having a blank project

floral onyx
leaden ice
#

that is what dividing by zero is, yes

#

it's when you divide by zero

simple egret
#

Oh lord I just clicked the link to the script
What a terrible day to have eyes

floral onyx
#

Ok, thanks, but what if it's required you to divide it by zero? I mean, if the output is 0 and that output is to be divided by other output?

crude mortar
#

computer can't divide by 0, so you must not do it in your code

#

you can check for division by 0 and stop it before you tell the computer to do it

leaden ice
simple egret
#

Dividing by zero is not defined, even in real life math

#

We don't know what it does

spring creek
floral onyx
#

I tried to change this method to codes, I do exactly like the formula.

leaden ice
#

"How big will each slice of cake be if I divide it into 0 pieces?"
"How many pieces of cake will we get if we cut it into pieces of size 0"?
This is what divide by zero is asking, and it's meaningless^

simple egret
#

Subtract 0, infinitely

crude mortar
#

there are no rules to say "do not do it" in real life with formulas, it will just give undefined result

#

but when translating it to code you need to do some extra precautions to stop division by 0

#

since computer is not a human who can recognize that dividing by 0 is bad and avoid it for you

spring creek
floral onyx
#

So how do I take extra precautions to stop division by 0? Is there any example?

leaden ice
simple egret
#

The formula paper you showed here has an issue, what if x = b in the 3rd example? Does it take the second or third case of the formula here? It's also why you can didvide by zero, the conditions should be "less than", and not "less than or equal to"

leaden ice
#

a good example is calculating averages:

int numberOfObjects = someArray.Length;
if (numberOfObjects == 0) {
  // we can't do the normal formula here since it would be dividing by zero
  average = 0; // some reasonable default?
}
else {
  float sum = 0;
  foreach (float x in someArray) {
    sum += x;
  }
  average = sum / numberOfObjects;
}```
floral onyx
simple egret
floral onyx
#

Ohh

#

So rather than this:

else if ((0.1 * maxNyawaPemain) <= nyawaPemain && nyawaPemain <= (0.4 * maxNyawaPemain))
{
// do something
}

I should do:

else if ((0.1 * maxNyawaPemain) <= nyawaPemain && nyawaPemain < (0.4 * maxNyawaPemain))
{
// do something
}

simple egret
#

Yeah that's one of the two ways. Just make sure the <= is always on the right here

floral onyx
#

Okay, I will think about it

gray mural
#

hello, do lot's of games use jwt in their games for authentication?

#

we have had this conversation earlier actually

flat wing
#

!learn

tawny elkBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

gray mural
flat wing
#

Nop

pure cliff
pure cliff
gray mural
#

can I combine sqlite db with jwt?

pure cliff
#

you sound like what you want is an Asp.Net Web API, which has built in easy support for JWT authorization

mighty yew
pure cliff
mighty yew
#

probably something like that yeah, What i was planning on is having a parent class with functions like "onAttack" "onDodge" "onDamaged" etc, and every item overiding these functions or the players stats or something.

pure cliff
#

that sounds very difficult to maintain, I would invert that entirely

gray mural
pure cliff
# mighty yew how so?

Your inventory items shouldnt be aware of the world outside of em, they just prolly have some kind of MutatePlayerstats function or whatever

Logic for what your Playerstats actually mean should exist in some kind of other place

#

Your inventory items should be "Is a" classes, not "does a" classes

#

Try and always seperate your classes into 2 bins:

  1. "Is" something (I call these Models)
  2. "Does" something (I call these Services)

Try not to overlap the two, Services can manage, CRUD, Read from, and Mutate models.

Models just sit and look pretty and hold your information, but they dont "do" things

#

I typically follow the paradigm that my MonoBehaviors are largely all my Models, and my Services are POCOs... mostly

mighty yew
#

While that's fair, i think you might misunderstand. almost every item will be unique and not every item just affects stats. For example, an item might spawn a gernade that drops on the floor every time the player makes a critical hit, or an item might regenerate the players health every time he dodges.

#

for every item i'll need a unique function that does something every time the player does something

pure cliff
# mighty yew While that's fair, i think you might misunderstand. almost every item will be un...

yeah so, visually that can happen, but I would strongly encourage you to design your code so your GrenadeMakerModel doesnt actually make the grenade.

It can perhaps have the SpawnsProjectile strategy, and it can have SpawnedProjectile = GrenadeModel, and perhaps ProjectileCount = 1

But the logic of spawning the Grenade should prolly be on your ProjectileService which manages CRUD for all your Projectiles... etc etc

smoky basalt
#

i have a ui rectTransform that i manually have to add to the clamped background size so that the camera moves to the edge and the player can walk to the edge of the background without blocking part of the background...when an aspect ratio is changed on a diferent monitor the background starts showing. how can i always add the size of the ui to the background so it is correct on any screen size? first image shows 1920x180, the second image is the other size 1280x720 and the ui is slightly a different size

float minX = mapMinX + camWidth;
float maxX = mapMaxX - camWidth + 5.07f;


        
float minY = mapMinY + camHeight;
float maxY = mapMaxY - camHeight;

float newX = Mathf.Clamp(targetPosition.x, minX, maxX);
float newY = Mathf.Clamp(targetPosition.y, minY, maxY);

the code clamps the camera to the background but then adds the x value of the ui manually. how can i make this work with every aspect ratio. the +5.07f is to make sure the ui is at the edge. but this number doesnt work for other sizes

pure cliff
smoky basalt
pure cliff
mighty yew
# pure cliff yeah so, visually that can happen, but I would *strongly* encourage you to desig...

I don't really know what you mean by ProjectileService, but I assume its a projectile manager for the whole game? don't really know why you would do that. I can see your point with the spawns projectile bit, that would work fine if I had a projectile manager, but that's just one of the many effects that can actually happen. If every item is going to be doing something unique, why not have unique functions for all of them? I can see how you would do something like this, but I don't really see why.

pure cliff
#

Render Mode

pure cliff
smoky basalt
pure cliff
crude mortar
mighty yew
pure cliff
#

IIRC all UI elements you create default to being in the... I think its literally called the UI layer, which is by default the front-most rendering layer

pure cliff
smoky basalt
pure cliff
#

@mighty yew if you have like, lets say 200 unique items, but you can actually just categorize them into say, 10 unique "strategies" or "behaviors" if you will, now you have 10 functions to write instead of 200.

Im sure you can see the appeal of that ;P

smoky basalt
pure cliff
#

the bottom in that list is the front-most, and the top layer is the backmost

smoky basalt
#

ahh okay ui is just hardcoded in unity so ill make my own ui option

pure cliff
somber nacelle
pure cliff
#

or wait can you modify it

#

I thought you can, maybe you cant

crude mortar
crude mortar
#

it is just a 32 bit mask for all layers, the ordering happens separately

pure cliff
#

@smoky basalt do yourself a favor and put UI layer at the very bottom XD

pure cliff
#

in that editor

smoky basalt
pure cliff
#

Im thinking of rendering order layers arent I

#

yeah thats the other layers isnt it lol

smoky basalt
#

i even moved the canvas to the bottom of hierarchy

somber nacelle
pure cliff
#

@smoky basalt sorry mate those layers are the physics one, for sprite rendering order stuff theres a totally seperate group of layers you gotta edit

clever bluff
#

hey Team, new to the server. Looking to post about inviting any interested Dev to join our** BlackThornProd team project: 7 Devs Build a Game WITH COMMUNICATION**.
Is there an appropriate channel where I can post it with all the details?

pure cliff
#

its in that same editor though IIRC, at the top theres uh... "Sorting Layers" Or whatever they are called

smoky basalt
#

ohh for sprites

tawny elkBOT
smoky basalt
smoky basalt
#

thank you lmaooo

pure cliff
#

they really outta rename "Layers" to be like "Physics Layers" or whatever

#

I dunno if they get used for stuff other than that

smoky basalt
thorny onyx
#
        var c1 = spectrum[3] + spectrum[5] + spectrum[4];
        if (c1 < 0.0002f)
        {
        //    player.GetComponent<playerMovement>().noise = false;

        }
        if (c1 > 0.0002f)
        {
            player.GetComponent<playerMovement>().canMove = true;
            Debug.Log(c1);

        }``` in this snippit, canMove is not being set to true, but the debug is showing
smoky basalt
#

this is when its 1920x1080 other ratios dont work

somber nacelle
smoky basalt
#

im clamping the ui to add onto the background so the camera can go past, but adding the rectTransform didnt work because the image isnt a sprite

mighty yew
somber nacelle
smoky basalt
pure cliff
mighty yew
pure cliff
mighty yew
#

Alright, it's going to take me a minute to read up on those since I haven't heard of them before.

pure cliff
#

so something like

public interface IHealthBehavior {
   int HealthModifier { get; }
}
public class HealthPotion : MonoBehavior, IHealthBehavior {
    [SerializeField]
    private int healthModifer;
    public int HealthModifier => healthModifier;
}

Something like that

#

but then if you want to add the IThrowableBehavior to the HealthPotion, to enable it as a "throwable item" as an example:

public interface IHealthBehavior {
   int HealthModifier { get; }
}
public interface IThrowableBehavior{
   int MaxThrowDistance { get; }
}
public class HealthPotion : MonoBehavior, IHealthBehavior, IThrowableBehavior
{
    [SerializeField]
    private int healthModifer;
    public int HealthModifier => healthModifier;

    [SerializeField]
    private int maxThrowDistance ;
    public int MaxThrowDistance => maxThrowDistance ;
}

boom, now it "identifies" as both modifies health and is throwable

#

and you just sort of aim to break up your various "behaviors" into interfaces, and can apply any amount of em to any given item

mighty yew
#

Where is the actual "throwing" or "healing" code stored?

pure cliff
#

Honestly a lot of this though could be boiled down to just a Flagged enum which I think Unity can serialize? IIRC it serializes to like, a list of checkboxes?

#

you could then add a bunch of nullable properties for every behavior, and then your editor hides/shows the properties if you have a flag checked off or not

#

itll be a bit more cumbersome potentially but might be easier to work with in the consumer

mighty yew
latent latch
#

What would be the benefit of this over a general inheritance approach and virtualization. I probably don't take advantage of interfaces that much beyond using them for type identity when using generics and stuff.

pure cliff
#

you can, however, implement multiple interfaces

latent latch
#

Right, but say, Item -> HealthPotion

#

Actually, ok yeah I can see the usage of interfaces this way

#

Rather, it would probably make more sense to do some inheritence here, and tack on the throwable interface on the inherited class

pure cliff
#

Flagged Enum is also totally valid, but you'll wanna do some fancy work with the enabling show/hide of your various fields based on enum values selected

jaunty sleet
#

Has anyone ever had issues serializing an object with a Dictionary as a property using Newtonsoft Json Utility? I have an object with a Dictionary property that I know has items in it, but when I save it in a json file it is empty. I have no clue why 😭

pure cliff
latent latch
#

Man, I really want to dive into ECS but too committed to my projects

pure cliff
#

I gotta jet in a sec, I got a technical interview for a new job but feel free to ping me with questions still, but prolly wont be back for an hour

mighty yew
#

It's alright, i'll try to make some sort of sense of this

pure cliff
#

god I hope its not just a bunch of "re-write quicksort from scratch, now write code to invert a binary tree" type of stuff, nngh

jaunty sleet
mighty yew
#

im not really sure on the enum thing, and i'm almost certain that it would make this several times harder, but the interfaces are actually pretty helpful

pure cliff
jaunty sleet
#

I have been trying but I haven't found the reason

mighty yew
#

im imagining I can have an item interface that every item inherits from, and then a "healthchange" or a "on-hit" interface that only certain items inherit from

pure cliff
mighty yew
#

and then I can just have a list of items? im hoping I understand this

pure cliff
#

you dont inherit from interfaces, they are more like a contractual obligation your class says it will adhere to.

You "implement" an interface, and "inherit" from a class

#

basically when you go

MyClass : IMyInterface

You are committing to MyClass implementing whatever IMyInterface said it has to implement

#

like a contract MyClass has signed and promised to adhere to, and if it doesnt, it throws a compile time exception and wont compile, and says "Yo, you said you'd do this thing but you didnt"

mighty yew
#

Ok, that makes sense

latent latch
#

An example of an interface I use is one I call IEntity, such that any script that implements it will be guaranteed to have a Stats object, an Ability class object, and an Equipment class object. This is helpful in unity because instead of checking for specific components of a gameobject, I can simply check if it includes this interface, making operations easier when doing sphere casts and such. Additionally, instead of exposing a script completely, this reference will only allow you to access what the interface implements.

fervent jacinth
#

how can i check if theres an object in this cone?

#

or put planes along the sides

floral onyx
latent latch
fervent jacinth
#

im using ezy slice, so i want to put planes along the sides and cut the things intersecting with the camera border

#

basically clearing the mesh in front of the cam

trim ferry
#

guys im having a problem here, i made a Player movement system, it works perfectly, but when i restart unity, the vision only moves in the X axis.. Here's the script btw: https://hatebin.com/rprqcbrcih

#

and if i dupllicate the player and delete the original one, it goes back to normal.

latent latch
# fervent jacinth im using ezy slice, so i want to put planes along the sides and cut the things i...

https://www.youtube.com/watch?v=XrqesjfcitU
Zero actually has the idea about locating what's in vision of the camera, but even with that information, you'll have to figure out the bounds relative to the camera of the object you want to trim.

Let's explore how you can detect when an object is inside the players camera view by using the camera's frustum and axis-aligned bounding boxes (AABB). This takes advantage of Unity's built in GeometryUtility class that provides some helper functions to make this easier.

The fi...

▶ Play video
fervent jacinth
#

im trying to create something like this, so i dont know if thats what i need https://www.youtube.com/watch?v=8rr83zwzlOA&t=1s

This is a nice visual illusion game mechanic. The original game is called Viewfinder. Make sure to check it out.

🔊 200 Likes! 🔊
⚠️ Alright, as people are really eager to know how the code works, I'll do a long stream soon and will code this whole thing from scratch because I can't share the code due to a paid package I'm using the cut the meshe...

▶ Play video
wooden cove
#

is there a simple way I can get an x, y output from a bool[,] depending on whether or not a certain element is true or false? I wanna get the indices in the array that are true

#

preferably without a for loop

leaden ice
#

but a better option may be to just use a HashSet<Vector2Int> in the first place, rather than a bool[,]

wooden cove
#

using a hashset would leave me without the data I need to verify if a field is taken

#

assuming I can make a class that holds a Vector2Int and bool and make a HashSet out of that is a better option, would that be the middle ground im looking for?

leaden ice
#
HashSet<Vector2Int> whiteSpaces = new() // or blackSpaces?? IDK which is which
bool IsTaken(Vector2Int space) {
  return whiteSpaces.Contains(space);
}```
#

the HashSet<Vector2Int> gets you everything you have now PLUS an extremely easy list of "taken" spaces (just iterate over the set)

wooden cove
#

ah I see, it would make more sense to me to invert the whole thing since I only need to know the open spaces tho. but th e logic is sound

#

keeping all positions in a hashset, and removing them when the spot gets filled @leaden ice

leaden ice
#

yeah that works

wooden cove
#

are HashSets serializable to the editor?

leaden ice
#

not directly

#

you will have to serialize it as a list

#

and read it into the HashSet in Awake

wooden cove
#

in that case I might keep the 2D array for the initializing data and convert to a hashset to manipulate

leaden ice
#

yeah

#

or that

#

but 2D arrays aren't serializable either

#

only 1D arrays

#

you could use an array of Vector2Ints, or a list of them

wooden cove
#

I should note that I am using Odin Inspector, so a lot of the serialization limitations are not applicable here

leaden ice
#

oh

#

ok

#

if you're using Odin

#

then HashSet probably works directly

#

try it

wooden cove
#

I was also just thinking that

lucid wigeon
#

Do you use assertions (Assert.IsTrue()) in code or rather exceptions for cases which should not happen like "Trying to add vehicle to inventory" (what should be already disallowed somewhere else)?
Assertion seem to be convenient to spot invalid states or bugs in the code but after they are removed in build the game might end up in some weird state if that condition is met somehow...

leaden ice
#

If that exists then it seems like it should work out of the box

wooden cove
#

altho im quite certain it will be serialized to JSON by default

#

same as with dictionaries

leaden ice
#

Odin is a thing that I own that I always forget about 😆

wooden cove
#

haha

#

we use the serializer and validator for our projects

#

validator is quite a powerful tool we have in the pipeline

#

serializer is nice, but most of the inspector stuff it provides can be done manually without relying on it.
It does really speed up my tool production tho

smoky basalt
#

does anyone know how to calculate the size of a ui element in the canvas. it says the width is 846.2356 but i need the actual sprite size which is 5.07f how is this conversion done?

leaden ice
smoky basalt
#

i know rectTransform is different from transform

#

i just dont know how to get the transform size of a rectTransform

leaden ice
#

what does "transform size" mean in your mind?

smoky basalt
#

this is 14.13 if its a rectTransform its based on width

leaden ice
#

that's a position

#

but

#

It's more complicated than you're thinking.
The coordinates of the RectTransform are in Canvas space, not world space. And the conversion between canvas space and world space depends on the canvas render mode

#

as well as the canvas scaler

#

so - maybe you could explain exactly what you're trying to accomplish here?

wooden cove
#

I was about to ask for clarification as well, its a bit unclear

smoky basalt
#

if you would please look in #📲┃ui-ux you would see my issue. im trying to clamp the camera to the background but the canvas overlays. i want to add the canvas to the x so that the clamp also shows the background+ the canvas

steep scarab
#

hey guys sorry for double question but I posted this in #💻┃code-beginner before a huge code block and it kinda got skipped, but I just need to know how would I go about getting the horizontal FOV of my camera in degrees? camera.FieldOfView returns the vertical fov in degrees, which as can be seen here works fine for moving the center of my vignette, however I need to find a separate value for the horizontal FOV for the scope thingy I'm doing so it scales correctly horizontally

leaden ice
vagrant oyster
#

There's also a function in Camera

#

But they should work the same

Correction: The formula is far more complicated (https://en.m.wikipedia.org/wiki/Field_of_view_in_video_games#Field_of_view_calculations), and you should use the Unity function.

In first person video games, the field of view or field of vision (abbreviated FOV) is the extent of the observable game world that is seen on the display at any given moment. It is typically measured as an angle, although whether this angle is the horizontal, vertical, or diagonal component of the field of view varies from game to game.
The FOV...

steep scarab
leaden ice
#

the formula might not be as simple as I said

#

it was just my first instinct

steep scarab
steep scarab
somber nacelle
#

that's a static method not an instance method

steep scarab
somber nacelle
#

call it directly on the class, not on an object reference. it's just Camera.HorizontalToVerticalFieldOfView(<parameters>)

steep scarab
#

thanks lol

somber nacelle
#

also your local variable is misleadingly named, it should be verticalFov not horizontalFov since that method returns a vertical fov

#

ah wait, you're just using the wrong method actually. you want the VerticalToHorizontal one since mainCam.fieldOfView is the vertical fov

steep scarab
#

appreciate it tho man thanks I feel dumb asl now tho lol

shadow hedge
jaunty sleet
#

Hey @somber nacelle, do you know why an objects properties that have values would be empty upon the object being serialized into a json file? This problem is actually driving me insane

#

No matter what I do there are no values in the json file even though there are values there before it is converted

somber nacelle
#

don't ping people into your questions

jaunty sleet
#

ok

lean sail
jaunty sleet
#

It's kind of ugly rn because I have been trying a bunch of things to fix it. But the problem hasn't changed at all

#

The methods in this file are also called by my game manager script, but I have printed out the values to confirm that they are there, and it really isn't empty

hidden parrot
#

first guess, i dont think newtonsoft serializes auto properties

somber nacelle
#

this won't fix your issue, but lines 39 through 47 can be reduced to just

string[] enemyIDs = enemyStates.Keys.ToArray();
bool[] enemyStatuses = enemyStates.Values.ToArray();
lean sail
hidden parrot
#

hes not

jaunty sleet
#

I was using newtonsoft, I tried json utility to see if it would work and it didnt either

hidden parrot
#

jsonconvert is the newtonsoft one

#

jsonutility is base

somber nacelle
lean sail
hidden parrot
#

Ah.

jaunty sleet
somber nacelle
#

try with fields instead of properties

jaunty sleet
#

I have tried that. Aren't properties supposed to be serializable?

somber nacelle
#

not with JsonUtility 😉

jaunty sleet
#

I was using newtonsoft before and it didnt work

hidden parrot
jaunty sleet
#

I am just going to put it back to newtonsoft as well bc jsonutility isnt helping

#

I would make backing fields as a work around if having fields worked

#

Changed to fields and newtonsoft, this is the output in the file: {"EnemyIDs":[],"EnemyStatuses":[]}

#

Originally I wasn't converting my data into arrays and just leaving it in a dictionary, which is supposed to be supported by newtonsoft. I only chaanged it to this because it wasn't working

#

I am just completely lost here

#

Ok I think I figured it out. The method is being called twice which somehow results in the output being empty. Idk how that is happening though

smoky basalt
#

Hello im using rigidbody moveposition to move my enemy toward the player but for some reason they start slowing down as they reach the player. is there a way to keep the speed. i think they are faster the further away they are from the player as well which i dont like

            Vector3 dir = (player.position - rb.transform.position).normalized;
            //Check if we need to follow object then do so 
            if (Vector3.Distance(player.position, rb.transform.position) > minDistance) {
                rb.MovePosition(rb.transform.position + dir * speed * Time.fixedDeltaTime);
            }
jaunty sleet
#

Does anyone know why the buttons from this script are double triggering? I have no idea why this happens. ```using UnityEngine;
using UnityEditor;
using System;

public class TestingMenu : EditorWindow
{
public static Action saveEnemyState, loadEnemyState, addEnemy;

public static string EnemyID { get; private set; }
public static bool EnemyState { get; private set; }


[MenuItem("Window/Testing Menu")]
public static void showWindow()
{
    GetWindow<TestingMenu>("Testing Menu");
}

void OnGUI()
{
    GUILayout.BeginHorizontal();
    if (GUILayout.Button("Save Enemy States")) saveEnemyState();
    if (GUILayout.Button("Load Enemy States")) loadEnemyState();
    GUILayout.EndHorizontal();
    GUILayout.BeginHorizontal();
    if (GUILayout.Button("Add Enemy")) addEnemy();
    EnemyID = EditorGUILayout.TextField("Enemy ID:", EnemyID);
    EnemyState = EditorGUILayout.Toggle("Enemy Is Alive:", EnemyState);
    GUILayout.EndHorizontal();
}

} ```

#

This is the cause of my problem from earlier

somber nacelle
smoky basalt
somber nacelle
#

no

smoky basalt
#

awesome ill just try using addforce and see if that works better

jaunty sleet
#

Does anyone know if GUI layout buttons in Unity editor windows normally double trigger when clicked? Or am I doing something wrong here?

lucid wigeon
#

Lol, my brain is dead. Instantiating a plain class with [Serializable] should work like that or not? I cannot comprehend how is that possible: values chunkWidth and chunkHeight are serialized properly with 50. In debugger they are set to 50. But my array inside this object is instantiated using other values (12,10,12). But I create this array in the constructor. And the values which are used for this are serialized properly. I cannot comprehend this. When I call this ResetCubes() from outside script in Start() method then it works. PU_PeepoBigBrain

somber nacelle
#

unity cannot serialize multidimensional arrays

jaunty sleet
#

To serialize multimensional arrays, you can make a struct with an array as a field

#

make the struct system.serializable

#

then make an array of the struct

#

That will allow you to have a multidimensional array in the editor window

lucid wigeon
#

no, i don't want to serialize it, I'm creating a new one in the constructor

lucid wigeon
jaunty sleet
#

You should upload the code, it would be easier to understand then screenshots

lucid wigeon
#

Right

somber nacelle
lucid wigeon
somber nacelle
#

why don't you do some debugging and find out

jaunty sleet
#

also boxfriend have you ever had an issue with GUILayout buttons triggering twice?

somber nacelle
#

i don't use it so i don't have info about it. if i knew the answer to your question i would have already provided it

jaunty sleet
#

Ok, thanks

#

That's so weird that it does that. So now I have to go set up some stupid boolean thing to make it not trigger the second time? It doesn't make sense lol

lucid wigeon
#

looks like the constructor is called

jaunty sleet
#

Yeah, I don't see why it being serialized would prevent the constructor from being called when using the new keyword

somber nacelle
leaden ice
#

so your width/height etc will not be set when the constructior runs

#

you can't really rely on the constructor in the context of serialization in Unity

lucid wigeon
#

I suppose the instance is first created and then public vars are set by the serializer

#

I have assumed that the public vars will be already set to inspector values when the object is instantiated

somber nacelle
#

this is why using the debugger is important. so you can see what exactly is happening and when

lucid wigeon
#

so I suppose it's not worth doing anything meaningful in the constructor if using plain classes because that's bug prone

somber nacelle
#

don't do anything that relies on any of the serialized values in the constructor

lucid wigeon
#

ok, thanks for help

sharp sky
#

Quick question. A while ago I had been using visual studios and it had given me some useful help in coding. For example I would be typing "public Vect" and it would predict and give different options that I can finish it with such as "Vector3" and all these would be a light green/blue color. However, now my new version does not do that at all nor does it have the lettering green/blue making it blend in with a lot of other code. Is there an option somewhere to turn that on again?

somber nacelle
#

!ide

tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

sharp sky
#

Thanks!

topaz sapphire
#

im in one helluva delema. I want to make a progressive shotgun reload (reload shell by shell over time until full, but can be fired at anytime during reloading as long as there is one shell in the gun) I use a coroutine to time the reloads then call a function to manage the change in ammo and call the corutine again to prepare the next reload. I am indecisive on how to cancel out of reloading, do I just clear the coroutine and prevent reloading with a change in boolean?

spring creek
lean sail
vocal root
#

Hi, im making a script to read text from a txt inside the resources folder. I just read that using resources folders is not recommended so Im asking if this is true

leaden ice
#

Basically everything in Resources will be loaded into memory immediately when the game starts

#

So it's bad for memory usage if you only need the data sometimes

vocal root
#

well i need the text to put it inside a list at the start so its just once

leaden ice
#

Any reason you can't just drag and drop it into your list?

#

As a TextAsset

vocal root
#

I want to have a txt to add more words in time

#

and if i change something in the script the list just clear itself so i dont want to write that much

#

i mean if i change the name of the list and that kind of things

ocean oasis
#

I gotta reask this because I don't think anyone ever had any ideas on it, but I used this tutorial to make soft body objects; it worked perfectly:
https://www.youtube.com/watch?v=W3x143cYF88&start=197
But then I made a simple script to scale the localscale with time, and while growing, the objects' spring joint completely just let go and the thing collapses, while growing. It become's a rigid soft body again once it's done growing.

Soft Body 2D Tutorial Jelly Effect - Unity (Easy)

Tutorial from Binary Lunar: https://youtu.be/H4MTeKT0QFY

Music used in this video

Boogie My Woogie no copyright Piano Boogie, royalty free 1940s Swing
royalty free Music by Giorgio Di Campo for FreeSound Musi...

▶ Play video
wicked wagon
#

Is there a difference between these?


  private void Update()
  {
      currentZoomState = inputManager.Zoom;
  }```
  ```private void Update()
  {
      bool currentZoomState = inputManager.Zoom;
  }```
ocean oasis
#

in the first one, there is a single variable that is created, and then updated each frame

somber nacelle
ocean oasis
#

in the second one, the variable is deleted at the end of each frame and recreated

somber nacelle
#

i recommend looking up variable scope to understand how it works

ocean oasis
#

^^^

leaden ice
pure cliff
wicked wagon
#

alright guys thank you all

topaz sapphire
pure cliff
#

Can even do a custom importer for a type of file extension you specify for your text file, and then it imports it instead as your actual output object type you need it to end up as

vocal root
#

no way to dump a txt file into a list without reading it on resources then?

pure cliff
#

As I just said above, you can instead make it an asset and change file extension

#

And use custom importer to convert it to your actual object you need it to be

#

Thus you "preload" all that work and compile it in, so you aren't doing all that work on boot up

slate trellis
#

I have this code right here:

if (Physics.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition)/* start position */, Vector3.down /* direction */, out RaycastHit hitInfo /* hit location info */, maxDistance, layerMask))
        {
            transform.LookAt(hitInfo.point);
        }```
I have a sprite in a 3D world view and I want it to rotate to where my cursor is. I have tried countless methods found on forums, video tutorials and a suggestion by a partner of mine. nothing works. I cam up with this solution, but I found out about a bug(?).
`Camera.main.ScreenToWorldPoint(Input.mousePosition)` this returns a static value relative to the player's position and not where the mouse is. I tried applying it to different GameObjects, even an independent one, but this seems to be a reocurring issue. I am requesting for a solution to my problems.
#

verison is 2022.3.5f1 LTS

topaz sapphire
#

☝️

#

k boss

slate trellis
quartz folio
#

Input.mousePosition is (x, y, 0) which will always return the camera position

#

If you want to cast a ray out of the screen where the mouse is, use

Ray ray = camera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))```
vocal root
slate trellis
#

found the solution, thanks!

opal bluff
#

I have an issue, when i push S to turn the bool "isPogoing" on the input becomes true, and it triggers fine, but if i hold down S the bool stays true for a while an doesn't switch off even if i let go of the key, i've fixed the problem by removing verticalinput which gets the y axis, but i need it for controller support so im confused how to fix it, heres my code if (Input.GetKey(KeyCode.S)||verticalInput<0) { isPogoing = true; isAttacking = false; } else { isPogoing = false; isAttacking = true; }

topaz sapphire
#

trying to make a shotgun spread, any advice on how to make this work? is there a project on to plane that this will work with or? or am I just dumb?

somber nacelle
#

!code 👇 because attempting to read that font is a pain in the ass

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.

cosmic rain
topaz sapphire
# somber nacelle !code 👇 because attempting to read that font is a pain in the ass
    public Vector2 spreadArea = new Vector2(1,1);
    bool readied = false;


    public override void weaponFunctionShoot(Transform origin, GameObject bullethole)
    {
        reloading = false;
        base.weaponFunctionShoot(origin,bullethole);
        for (int i = 0; i < pellets; i++)
        {
            var spreadAreaTrue = new Vector3(Random.RandomRange(-spreadArea.x, spreadArea.x), Random.RandomRange(-spreadArea.y, spreadArea.y), (Random.RandomRange(-spreadArea.x, spreadArea.x)));
            var dir = spreadAreaTrue + origin.transform.forward;
            if (Physics.Raycast(origin.transform.position, dir, out RaycastHit hit, 99))
            {

                Enemy hitTarget = hit.transform.GetComponent<Enemy>();

                if (hitTarget != null)
                {

                    hitTarget.takeDamage((weaponData.damage) / pellets, transform.parent.parent.parent);
                }
                else
                {
                    Instantiate(bullethole, hit.point, Quaternion.Euler(0,0,0));
                }
            }
        }
        
    }```
somber nacelle
#

!cs

tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
quartz folio
#

Is this your own Random function 🤔
Oh it's just using the obsolete one for no good reason

topaz sapphire
# somber nacelle !cs
public int pellets = 1;
    public Vector2 spreadArea = new Vector2(1,1);
    bool readied = false;


    public override void weaponFunctionShoot(Transform origin, GameObject bullethole)
    {
        reloading = false;
        base.weaponFunctionShoot(origin,bullethole);
        for (int i = 0; i < pellets; i++)
        {
            var spreadAreaTrue = new Vector3(Random.RandomRange(-spreadArea.x, spreadArea.x), Random.RandomRange(-spreadArea.y, spreadArea.y), (Random.RandomRange(-spreadArea.x, spreadArea.x)));
            var dir = spreadAreaTrue + origin.transform.forward;
            if (Physics.Raycast(origin.transform.position, dir, out RaycastHit hit, 99))
            {

                Enemy hitTarget = hit.transform.GetComponent<Enemy>();

                if (hitTarget != null)
                {

                    hitTarget.takeDamage((weaponData.damage) / pellets, transform.parent.parent.parent);
                }
                else
                {
                    Instantiate(bullethole, hit.point, Quaternion.Euler(0,0,0));
                }
            }
        }
        
    }```
topaz sapphire
somber nacelle
#

are you using an ancient version of unity?

topaz sapphire
#

2021.2

quartz folio
#

Then it's not "the one in the manual"

#

it probably also tells you what to use if you hover over it, it's gotta be underlined for a reason

opal bluff
#

like if i hold down the bool for too long it stays true for a long time

cosmic rain
opal bluff
#
        {
            isPogoing = true;
            isAttacking = false;
        }
        else
        {
            isPogoing = false;
            isAttacking = true;
        }

        if (verticalInput < 0)
        {
            isPogoing = true;
            isAttacking = false;
        }
        else
        {
            isPogoing = false;
            isAttacking = true;
        }```
cosmic rain
#

That's not what I suggested.

#

You still need to check wether the controller is used or not.

opal bluff
#

vertical input calls the y axis which basically uses the controller input tho?

#

is there another way?

cosmic rain
opal bluff
#

no i mean like I dont want the bool to be true when the button isnt being pressed like immediately, my problem is everytime i press the button for a little too long it stays true even if i let go, i want it to immedately become false when the player lets go, if i only have the button be S its fine, but for some reason verticalInput is making it true for longer even if i let go of the buttton, i want the isPogoing bool to be false as soon as the player lets go of the button

cosmic rain
somber nacelle
opal bluff
#

yea i dont know why tho

cosmic rain
opal bluff
#

verticalInput = Input.GetAxis("Vertical"); i put it in the update function and the code above is in update as well

#

but thats how im calling the verticalinput

topaz sapphire
#

that cant be too large can it

somber nacelle
#

is that what they show they are in the inspector?

topaz sapphire
somber nacelle
# topaz sapphire

in that case i don't see why you need the three Random.Range calls when you could just use Random.insideUnitCircle and set z to 0 (unless you want it to potentially shoot backwards, in which case keep your z as it is i guess)

topaz sapphire
opal bluff
peak musk
opal bluff
#

hm how come

#

its snapping it on and off i had getkeydown and getkeyup before but it just seemed like too much writing

peak musk
#

Just seems like a good trouble shooting step. you're already writing all the code out twice, it shouldn't be much less efficient to ask the program to check for GetKeyUp instead of a blanket Else, which has been finnicky for me in the past

opal bluff
#

ah okay thats a good point

pure cliff
#

So I am having a strange problem where my .editorconfig file is simultaneously being detected by Visual Studio and Rider, and yet not actually being applied to my code editor, and its very annoying because its causing my personal code style to just... be ignored on unity projects, so lots of stuff gets highlighted as a problem that I dont want highlighted.

Anyone had this before?

#

Its error'ing it as missing braces, but preferences clearly have loaded that to be not an error

hidden gulch
#

ok so i want to make interactables in my game
basically click: call a function in a script
thing is: i need the script name to be able to call functions in it, but the script names will be different bc the scripts are different and need different names for better identifying.
my solution to this was to get all scripts in the object(the object will only have the interact script in that case) and get the 1st script and call the function in it, but i have no idea how to do that. tell me if this is an xy problem and if there is a better sollution

#

this is my current code:

public class InteractTest : MonoBehaviour
{
    public bool open;
    
    public void SetState(bool newState)
    {
        open = newState;
    }
}
public class PlayerInteract : MonoBehaviour
{
    private PlayerInventory PI;
    public const float intRange = 4f;
    void Start()
    {
        PI = GetComponent<PlayerInventory>();
    }
    void Update()
    {
        if(Input.GetMouseButtonDown(0))AttemptInteract();
    }
    void AttemptInteract()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit rayHit;
        if(Physics.Raycast(ray, out rayHit, intRange, LayerMask.GetMask("Interactable")))
        {
            GameObject other = rayHit.collider.gameObject;
            GameObject curItem = PI.HeldItem;
        }

    }
}
leaden ice
#

and hook up the PointerClick event to your various script functions

#

(just make sure your camera has a PhysicsRaycaster on it, and your scene has an EventSystem in it)

hidden gulch
#

by eventsystem you mean something like this right?(i have absolutely no idea how this got into my scene but its here)

leaden ice
#

yes that

#

it gets added automatically whenever you add any UI element to the scene

#

you can also add one manually by GameObject -> UI -> EventSystem

hidden gulch
leaden ice
#

don't worry it's for non-ui stuff too with the approach I described above

hidden gulch
#

is the standalone input module also nescessary?

leaden ice
#

yes

hidden gulch
#

alr

hidden gulch
leaden ice
#

no

#

it's the input module for the old input system

#

there's a different input module for the new input system

hidden gulch
#

bc when i searched for the standalone input module i only found videos on the new input system

pure cliff
# hidden gulch ok so i want to make interactables in my game basically click: call a function i...

thing is: i need the script name to be able to call functions in it, but the script names will be different bc the scripts are different and need different names for better identifying.
A lot of what you just wrote there doesnt really mean anything in the context of C#. Id recommend getting more familiar with the lexicon of C# so you can better convey what you mean here.

"script name" isnt a thing in C#, Im not sure what you mean by "script name"

pure cliff
#

or at least typically "script name" would just be the file name

pure cliff
# hidden gulch file name

you shouldnt care about file names like that, you deal with "classes" in C#, which are declared in your files

hidden gulch
#

as filename

#

wait lemme reformulate the question

pure cliff
#

largely speaking... you shouldnt really be even discussing handling file names at all in this context

hidden gulch
#

is FileName VarName = new FileName; correct or is ClassName VarName = new ClassName; correct

pure cliff
#

the second one 🙂

hidden gulch
#

alr, thank you

pure cliff
#

pretty much always you keep your FileName.cs to be the same as the class you declare inside of it

#

and, furthermore, theres stuff other than classes in C# you can declare, like enums and interfaces

hidden gulch
pure cliff
#

Its typically a good idea to keep the names distinct so you dont mix them up

#

otherwise you will have a bunch of "Interact.cs" files in your tabs in your IDE and, how would you know which is which?

hidden gulch
#

wait can i just have a filename class and a interact class

#

and just leave the filename class empty?

pure cliff
#

lets start from the top

#

whats your actual goal, high level result in like, video game terms from someone playing your game

hidden gulch
hidden gulch
pure cliff
#

sounds good so far

#

whats the technical challenge you forsee, without talking about code yet but like, describing the problem in plain english

#

imagine you are trying to describe the problem to someone who doesnt know anything about C# yet

cosmic rain
hidden gulch
#

not beeing ironic or sarcastic, just makes it easier to explain

pure cliff
cosmic rain
pure cliff
#

"I want to do x, but the challenge is y" etc etc

#

(I already have a pretty good guess as to your issue because its a very common one that gets asked in here multiple times per day, but its good to get into the zone/habit of articulating challenges this way)

hidden gulch
# pure cliff Im sure I will understand but, just give it a shot first at describing the techn...

alr, i need to send a ray from the camera in the direction that the camera is facing, if that ray hits something that is in the "interactable" layer it will get the interact script inside it and execute its "Interact()" function. but to get the interact script inside it i need the file name of the interact script(because you need to specify the variable(that stores the script so you can call its functions) type), but if i name all files the same(so i always know the file name), ill get a bunch of "InteractScript.cs"'s in my editor and i dont want that, also i'd have to separate the files in different folders bc there cant be two same named files in the same folder.

pure cliff
hidden gulch
pure cliff
#

The handy thing here is GetComponent works with Polymorphism and Encapsulation

pure cliff
hidden gulch
pure cliff
#

but the long and short of it is, lets say you have:

abstract class FruitEntity : MonoBehavior { ... }

and then you implement some classes that inherit from it:

class AppleEntity : FruitEntity  { ... }
class BananaEntity : FruitEntity { ... }

If you put an Apple component on Object A, and Banana component on Object B, but if you use

otherObject.GetComponent<FruitEntity>();

It will work for both the Apple and Banana components, because they both are FruityEntitys

hidden gulch
cosmic rain
#

It's called inheritance

hidden gulch
#

so i need to create a parent class(lets call it interact) that will have basic interacting functions and subclasses that inherit from that class and those will be singular to objects

hidden gulch
spring creek
pure cliff
hidden gulch
pure cliff
#

The next thing to consider:

All of these objects, do they have common functionality? You can have many instances of the same class, but they behave differently simply by modifying properties/fields on them. The code can be the same, but just changing configuration of them changes how they act

#

Which means just 1 single file and then you make prefabs with that 1 component applied, and you just modify parameters on it to change its behavior

cosmic rain
hidden gulch
hidden gulch
pure cliff
spring creek
pure cliff
#

like you may perhaps have hundreds of interactables... but you can group em up into a small handful of types of interactables

cosmic rain
#

Hardcoding complex systems makes them hard to maintain.

hidden gulch
pure cliff
#

and all your NPCs also likely can just use a single "NPC Interactable" class, and you just customize some properties on that to define the behavior, what they say, etc

hidden gulch
#

alr, tysm for the help

#

ill go finish my code now

pure cliff
#

fair enough, point being is to start by thinking about if you can simplify your problem space down to be a lot smaller and easier to work with

hidden gulch
#

i shouldve have thought of this solution earlier tho, as i was trying to identify all the colliders in an object by using GetComponent<Collider>(); which is basically the same thought process

#

also i couldve just used GetComponent<MonoBehaviour>() if i was trying to do 1st solution i suggested, but idk if the transform or other components are inheriting from monobehaviour as its a common class so its probably not a good idea to do that

pure cliff
#

Now in other news, Im trying to sit here and reason out a bit of a puzzle, and Im sort of unsure how to proceed.

I have a 8 way movement topdown tile turn based game where theres a few ways the player can interact with picking their next action to perform.

By default its just moving, and I highlight an A* path to where their mouse is hovering to show where the character will go if they click, if its a valid tile they can get to. Otherwise, no highlighting.

I also have the ability to click abilities with cooldowns, which will switch to instead highlighting "valid" tiles they can click to use the ability on (IE, they can use roll which rolls em 2 tiles in a direction they choose, or shoot a bow in 1 of 8 directions, etc etc)

So once ability is selected, its icon swaps to a cancel button to swap back to the default move mode.

And, while in ability mode if they hover over a valid tile it turns green of course.

I am trying to figure out a clean approach to sort of handling all these possibilities in 1 nice flow of logic for what tiles are highlighted vs not, and whether to swap to "okay stuff is happening now"

#

I have 2 methods on my UIService that already facilitate drawing tiles:

  1. void ClearHighlights()
  2. void RedrawHighlights(Vector2Int origin, (Vector2Int Offset, HighlightColor Color)[] tiles)

So that part is solved, the second method draws the array of tiles with respect to the origin passed in as the first param

cobalt elm
#

I am participating in sebastian lagues chess challenge, I am trying to implement move ordering with no success. The times for each move increase drastically when I have move ordering enabled. I believe I have done everything right (supposedly) with my algorithm. I cannot find any issues. Any help is greatly appreciated. Thanks

    private Move[] OrderMoves(Move[] moves, Board board)
    {   
        for (int i = 1; i < moves.Length; i++)
        {
            Move current = moves[i];
            int j = i - 1;

            while (j >= 0 && ScoreMove(moves[j], board) > ScoreMove(current, board))
            {
                moves[j + 1] = moves[j];
                j--;
            }

            moves[j + 1] = current;
        }

        return moves;
    }

    private float ScoreMove(Move move, Board board) // Gives an estimated score of the move.
    {
        float score = 0f;
            
        PieceType subject = board.GetPiece(move.StartSquare).PieceType;
        PieceType target = board.GetPiece(move.TargetSquare).PieceType;
 
        if (target != PieceType.None) score = pieceVals[(int)target] - pieceVals[(int)subject];
        
        if (move.IsPromotion) score += pieceVals[(int)move.PromotionPieceType];
        // Square is attacked by a pawn.

        return score;
    }
hidden gulch
#

Now in other news Im trying to sit here

slate trellis
#

I am having a problem with cameras. I want to use the player to get in a car and then disable the player, resulting in the camera having to change angles from the player to the car. It throws me this error NullReferenceException: Object reference not set to an instance of an object. I have assigned all the correct values and objects in their referring scripts but it keeps showing it.
Here is the relevant code for the camera:

public void CurrentCameraLocation(CameraLocation newLocation)
    {
        if (newLocation == CameraLocation.Player)
        {
            player.SetActive(true);
            transform.position = new Vector3(cameraPosPlayer.position.x, cameraPosPlayer.position.y, cameraPosPlayer.position.z); 
        }   
        else if (newLocation == CameraLocation.Car)  
        {
            player.SetActive(false);
            transform.position = new Vector3 (cameraPosCar.position.x, cameraPosCar.position.y, cameraPosCar.position.z);
        }

        cameraLocation = newLocation;
    }```
Here is the relevant code for the car:
```cs
void Update()
    {
        if (rotate)
        {
            rb.freezeRotation = false;
        }
        else
        {
            rb.freezeRotation = true;
            transform.position = startPosition;
        }
    }```
and here is the relevant code for the player:
```cs
void OnCollisionStay(Collision collision)
    {
        if (collision.collider.gameObject.TryGetComponent<GetInCar>(out GetInCar getInCar) && Input.GetKeyDown(KeyCode.E))
        {
            cameraScript.cameraPosCar = getInCar.cameraPos;
            getInCar.rotate = true;
            changeToCar = true;       
        }
    }```
buoyant crane
#

Actually it looks like you already are in the server

#

You can go send the code there sadok

buoyant crane
slate trellis
#
void OnCollisionStay(Collision collision)
    {
        if (collision.collider.gameObject.TryGetComponent<GetInCar>(out GetInCar getInCar) && Input.GetKeyDown(KeyCode.E))
        {
//38        cameraScript.cameraPosCar = getInCar.cameraPos; // this line here
            getInCar.rotate = true;
            changeToCar = true;       
        }
    }```
cobalt elm
#

I’ve also asked for working code to analyze

#

Haven’t gotten any

#

I’ve looked at Sebastian’s himself and still can’t find what I’m doing wrong 😭

spring creek
slate trellis
#

I highlighted it with a comment

#

line 38

buoyant crane
slate trellis
#

What would you suggest to fix it?

spring creek
cobalt elm
#

actually getting some help right now @buoyant crane thx tho

slate trellis
#

it's an empty gameObj

spring creek
slate trellis
#

The camera script is placed on the camera holder

spring creek
#

If you have a public field (or one with [SerializeField]) i would just drag it in throught the inspector.

slate trellis
#

the Car and Player script are placed on the parent of the objects (Both empty objects)

spring creek
#

Otherwise you have to find it in the scene

slate trellis
#
[SerializeField] GameObject player;
[SerializeField] PlayerMovement playerMove;
[SerializeField] Transform cameraPosPlayer;
public Transform cameraPosCar;
public CameraLocation cameraLocation;
#

those are the variables

#

all dragged in place

buoyant crane
slate trellis
#
void OnCollisionStay(Collision collision)
    {
        if (collision.collider.gameObject.TryGetComponent<GetInCar>(out GetInCar getInCar) && Input.GetKeyDown(KeyCode.E))
        {
//38        cameraScript.cameraPosCar = getInCar.cameraPos; // this line here
            getInCar.rotate = true;
            changeToCar = true;       
        }
    }
#

I want to debug the highlited line

spring creek
#

And he means YOU debug it, in your ide and unity. Talking to people isn't debugging it

slate trellis
#

I feel confused

spring creek
#

Use debug.log or even better, use breakpoints

slate trellis
#

why is one person helping me and one lecturing me?

spring creek
buoyant crane
slate trellis
#

ik, but it get's confusing when 2 people try to make differing points

buoyant crane
#

cameraScript is the only thing that can be null in that line

slate trellis
#

which makes the one look like a lecturer

buoyant crane
#

fair

spring creek
slate trellis
#

thanks a lot

buoyant crane
slate trellis
#
[SerializeField] CameraScript cameraScript;
buoyant crane
slate trellis
#

yes

#

I just did and it fixed it, thanks a lot

analog aspen
#
  Vector3 right = transform.TransformDirection(Vector3.right);
 
  // Press Left Shift to run
  bool isRunning = Input.GetKey(KeyCode.LeftShift);
  float curSpeedX = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical") : 0;
  float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal") : 0;
        
  float movementDirectionY = moveDirection.y;
  moveDirection = (forward * curSpeedX) + (right * curSpeedY);```
Hello, how do I fix an issue where the player moves faster diagonally? Above is my code attached to character controller
cosmic rain
novel sundial
#

Of course, but this code is wrapping Netcode RPC calls so I definitely don't want it running every frame.

analog aspen
# cosmic rain You need to get the movement direction vector and normalize it before multiplyin...
Vector3 forward = transform.TransformDirection(Vector3.forward);
Vector3 right = transform.TransformDirection(Vector3.right);
 
// Press Left Shift to run
bool isRunning = Input.GetKey(KeyCode.LeftShift);
float curSpeedX = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical") : 0;
float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal") : 0;

float movementDirectionY = moveDirection.y;
Vector3 normalizedMovement = (forward * curSpeedX + right * curSpeedY).normalized;
moveDirection = normalizedMovement * Mathf.Max(Mathf.Abs(curSpeedX), Mathf.Abs(curSpeedY));

moveDirection.y = movementDirectionY;```
Is this alright?
analog aspen
#

yup

cosmic rain
# analog aspen ``` Vector3 forward = transform.TransformDirection(Vector3.forward); Vector3 rig...
  1. Instead of TransformDirection, you can use transform.forward/right directly.
  2. Not sure what that weird math is. You should get the input direction first from your input. Normalize it and then multiply by speed. I don't understand why you calculate movement separately for each axis..?
    All you need is:
Vector2 input = new Vector2(xAxis, yAxis);
input.Normalize();
Vector3 movement = input * speed;
#

Ah, if you follow my example, you'll need to transform the vector into the object space in the end.

latent latch
#

Trying to figure out the best way to make a list of unique values (enums) that can be serialized on the inspector for asset creation, which will also be read multiple times during runtime. The obvious answer you'd think would be a bitwise enum, but depending on the size of the enum, I'd have to loop over every bit to find all set bits before seeing if those keys exists in the dictionary. Any other suggestions?

cosmic rain
latent latch
#

Right, actually all keys do exists in the dictionary, but depending what's in the list will be what events I trigger

#

so if I had all entries of my flag enum filled up, that's quite a lot of looping each time I check it

cosmic rain
#

32 iterations at max. And you'd need to loop regardless. Even if it was an array or list of values.

latent latch
#

I guess I could just onvalidate and cache the exact keys

cosmic rain
#

Unless I'm misunderstanding your use case.

latent latch
#

right, i have to loop regardless if it's a bitwise enum, but if I just had a list of value I'd know for sure what those values are and the it would just be a O(n) operation

cosmic rain
#

I guess so. The tradeoff is between memory used and runtime complexity.🤷‍♂️

latent latch
#

I just hate using onvalidate honestly but that's usually the fix to the editor's shortcomings

cosmic rain
#

You can make a context menu function that you run manually.

#

Instead of OnValidate

latent latch
#

ah, hmm

fast belfry
#

Is there a way to do something when PlayableBehaviour starts? And I mean not when it's state becomes Playing, but when we reach it in the track. So basically do something on its first process frame.
Currently I check for whether the action has been taken. Is there anything built in for that? (OnGraphStart and OnBehaviourPlay don't work in that manner?)

dull yoke
#

Hey guys! My friend @magic island has a problem with this camera jitter/jumping. They already tried capping the FPS to 140 and 60 and changing Update() to FixedUpdate() and Time.deltaTime() to Time.fixedDeltaTime(). Both approaches didn't really solve the issue.
See video for what I mean, you can clearly see the jumping of the camera, even though we have lots of FPS / I move the mouse slowely.

fast belfry
cosmic rain
fast belfry
dull yoke
cosmic rain
#

A screenshot should be fine.

soft shard
#

One note with the profiler, the "Deep Profiling" mode can help check where GC.Alloc calls may be coming from, which can often contribute to performance issues as well, but its not enabled by default

magic island
dull yoke
#

Yes, we have never used the profiler, so we don't really know how it works or what we have to look out for

#

granted, we've never encountered that camera issue

magic island
#

something certainly causes some performance spikes

cosmic rain
dull yoke
#

Machine shouldn't be the issue, since we have tried it on 4 different devices, all of them using different hardware

#

Is it okay to share the camera script in here?

cosmic rain
#

Most of it seems to come from the editor loop.

cosmic rain
mossy snow
#

and profile an actual build too, to confirm you aren't chasing ghosts based on that last screenshot

cosmic rain
dull yoke
magic island
#

it plays a lot of videos actually

dull yoke
#

ah right, you are right

cosmic rain
# magic island

On this frame it seems like it's waiting for something on the GPU thread.

cosmic rain
#

Playing videos is not a "child's play". It's a serious business. If you run several players at the same time, they're gonna do some awful stuff to you.

magic island
#

yeah i should implement some code to only play them when i am near them, hopefully that fixes the issue

dull yoke
#

Alright, so that works good enough. We only play and load one video at a time minus the preloading we do when the app starts up. The performance spikes are almost completely gone - they still happen when you go near a videoplayer, though. It's not noticable enough to consider it annoying now. Thanks @cosmic rain for the advice!

distant barn
#

okay np

forest linden
#

speed = Vector3.Distance(transform.position, lastpos) / Time.deltaTime;
lastpos = transform.position

this is giving me the result 0 every time
I've debugged it and for some stupid reason transform.position and lastpos returned the same value (i debugged it between the spieed calc and the last pos change)
Why?

There are no other instances where i change lastpos

ashen yoke
#

is it in fixed update?

forest linden
#

no

ashen yoke
#

whats the type of speed?

#

move the whole thing to LateUpdate see if it fixes it

forest linden
#

ok, it worked.

#

strange tho

#

that usually always works in a normal update for me

ashen yoke
#

not strange, the issue is execution order

#

you are testing for transform change before it occured

forest linden
#

ah

#

ok

ashen yoke
#

i assume some other script moves the object

forest linden
#

the same

ashen yoke
#

are you moving it with physics?

forest linden
#

no

#

charactercontroller

ashen yoke
#

that is physics

#

its part of it, even tho doesnt look like it

forest linden
#

I guess its because it calculates collisions

ashen yoke
#

you may look into sync transforms online

#

that may work, i dont know

cosmic rain
#

We need to see more of your code. It's totally not clear what you're doing from that snippet and where/what you debug.

vocal root
#

Anyone knows a way to write at the start of a string? I need to add text above text in a string but I can't find anything on Google.

lean sail
vocal root
#

add text to the start of a string unity
tmp text inverse order
invert string order unity

#

All ive found is to put Line Spacing -1 but only works with old text not tmpro

#

And I just did it right with something I figured but its weird to not have something to reverse order in strings or texts

lean sail
#

All you need to do is concat the string like
someVar.text = someString + someOtherString
Possibly with a \n in there

vocal root
#

yeah i just did that, but i wanted something to just inverse

lean sail
#

Although you should use stringbuilder instead of any string concat to avoid allocations

crystal dagger
#

Heya

lean sail
#

You could probably just get the char array and call Array.reverse in that case, not sure if theres a more optimal method

vocal root
#

invert order

crystal dagger
#

Maybe a for that goes on reverse

lean sail
vocal root
#

or add the text to the start so it works the same for me

crystal dagger
#

for(int i = array.len, i < 1, i--)
array[i]

#

actually --

lean sail
#

Why add it to the start and then try to invert, instead of just adding to the end

vocal root
#

no no, its one thing or the other

#

i just needed one

#

im trying to make like a history of text written

#

and i want the newest at the start

#

but nvm i just did the concat of the previous history to the end so i add the new text at the beggining

lean sail
crystal dagger
#

So i need help

#
        float distance = Vector3.Distance(character.position, zombie.position);
        if (distance < 10)
        {
            Vector3 direction = zombie.position - character.position;
            Quaternion rotation = Quaternion.LookRotation(direction);
            head.rotation = rotation;
            rotation = Quaternion.Euler(character.eulerAngles.x, Mathf.Clamp(head.eulerAngles.y, character.eulerAngles.y-90, character.eulerAngles.y+90), character.eulerAngles.z);
            head.rotation = rotation;
        }

This is my current code, the goal is to look at the enemy when they're nearby

#

Problem is, at some angles, the head flips suddenly to the wrong direction

unborn pollen
#

Hi is there a way to apply a shader to the Unity UI?

I have a canvas screen space, which I can't change to another space it has to stay in this one.

I can't find a way to get a colorblind shader applied to this UI in this space.

Because the canvas screen space UI looks like it's rendered outside of the unity pipeline.

#

I also try to create my own scriptable render pipeline, but even if you create a null one and all the render is black, the canvas screen space is render over all the previus render.

sudden meadow
#

If I have a database of scriptable objects that contain object data, can I copy that SO class into an object in a smart way so that it's not a direct reference making me able to alter the SO variables without it reflecting on all other objects that use the same SO data?

I'm looking at ICloneable (https://learn.microsoft.com/en-us/dotnet/api/system.icloneable?view=net-7.0), do you think this would be appropriate??

unborn pollen
sudden meadow
#

Yeah I saw that when it came to deep vs shallow copy but that should be okay. I only need a shallow copy so I can alter a few variables. Thanks.

sudden meadow
#

Seems doing Instantiate might be a better idea. Clone worked. I could alter the variables and read them separately on each object, but for some reason the original also got changed.

steady moat
#

You should consider other pattern then copying a ScriptableObject.

sudden meadow
#

why

steady moat
#

Usually, you have something that represent the instance and something that represent concept.

#

By example, If I say: Give me X weapon, I'm talking about the concept. If I say give me the weapon of the player, I'm talking about the instance of the weapon.

#

Variable are different on both object.

#

In one situation, the variable is the same for every weapon that is associated with the given SO.

#

You can see this as the FlyWeight pattern.

sudden meadow
#

nah the reason i want a shallow copy is because i am storing behavior scripts as SO's for plug and play behavior scripting, and I want the behavior itself to have local internal playtime and behavior stage tracking.

steady moat
static matrix
#
 if (Input.GetKey(KeyCode.C))
                {
                    cam.transform.localPosition = new Vector3(cam.transform.localPosition.x, -2.5f, cam.transform.localPosition.z);
                    gameObject.transform.localScale = new Vector3(1, 0.5f, 1);
                    GetComponentInChildren<CapsuleCollider>().height = (3.089386f / 3);
               
               
                
                        speed = 5 + SpeedBoost;
                        SoundLevel = 25;
                
                
                }
                else
                {
                    if(!Physics.Raycast(transform.position, new Vector3(0, 1)))
                    {
                       GetComponentInChildren<CapsuleCollider>().height = (3.089386f);

                        gameObject.transform.localScale = new Vector3(1, 1, 1);
                            if (FB != 0)
                        {
                            cam.transform.eulerAngles = new Vector3(cam.transform.eulerAngles.x, cam.transform.eulerAngles.y, Mathf.Sin(TimerBob));
                        }
                        else
                        {
                            cam.transform.localPosition = new Vector3(0, (Mathf.Sin(TimerBreathe) * 0.13f), 0);
                            SoundLevel = 35;
                        }
                    }
                   
                }

(Code for @naive swallow )

#

somethings definitely happening becase the headbob and idle bob stop

naive swallow
#

I'm on mobile so reading that code is not really in the cards for me at the moment, but maybe pose the question again here and see if anyone else can assist

static matrix
#

wait hold on it started working

#

huh

#

well I guess I figured it out??

hidden gulch
#

how do i calculate the amount of torque needed to reach a certain rotation?

#

p.s. using rigidbodies

#

and door hinges

eager wagon
#

hi
I want to access a script from a prefab (public cannon cannonScr;), but it doesn't appear when I want to integrate it in the Unity inspector. Do I need to do it differently with prefabs?

fervent furnace
#

is your prefab in scene?

eager wagon
#

no

#

i Instantiate it

fervent furnace
#

try getcomponent?

eager wagon
#

??

fervent furnace
#

object in scene cannot reference script of prefab in folder but you can use get component to get its script when instantiate
or you have tried but it doesnt work

eager wagon
#

idk who to do this

#

i mean with a script

#

the fact is that i Instantiate a prefab and i want get a var from anotehr script

fervent furnace
#

you mean the spawner want to access some scripts on prefab? or another script not on the prefabs (on other gameObject)?

eager wagon
#

the boject i spawn (the bullet) i want to get a var from the gun scr

stark sinew
#

@hidden gulch

I'm not exactly sure, but maybe Kinematic Equations can help you.

You could also divide the amount of rotation by the amount of time you want it to take to get the needed per-frame rotation value, but idk if that's working properly with Rigidbody

hidden gulch
fervent furnace
#

oh so the prefab wants to access the variables on spawner script
declare a property on bullet's script and the gun pass its script to it
instantiate().getcomponet<>().gun script=this

eager wagon
#

i see

#

i think it should work

#

thx

eager wagon
stark sinew
#

@eager wagon
Could you show some code?

eager wagon
#

yep

#

GameObject cannonBallInstanciada = Instantiate(cannonBall, transform.position, Quaternion.identity).GetComponent<>()cannon.angles;

#

i trieed to replicate this
instantiate().getcomponet<>().gun script=this

stark sinew
#

Bro wtf is GetComponent<>()cannon 😄
That other person wrote some pseudo-code, you gotta make it fit for your project.
At this point, I think you're better off in the beginner channel!

someObject.GetComponent<SomeComponent>().someProperty = someValue;

Pseudo-Code, don't copy paste this, modify it accordingly!

https://m.youtube.com/watch?v=jGD0vn-QIkg&pp=ygUJQyMgYmFzaWNz

eager wagon
#

idk

#

just tried waht this guy said

eager wagon
stark sinew
fervent furnace
#

you already referenced to the object have you spawned so you can getcomponent on it

rigid island
stark sinew
#

@rigid island
Brackeys sucks.
But for someone who's mindlessly copying and pasting, it's enough to learn the basics!

rigid island
#

why link it lol

stark sinew
# rigid island why link it lol

Why not give some useful advice to this person instead of questioning mine?
You shouldn't complain about answers while you're not giving any on yourself!!

It's not about the specific Content Creator, it's about the severe need of learning the very basics, if you write something like GetComponent<>()cannon.angle you can pretty much watch Brackeys to improve.

Just search for C# Basics and there are probably 20 more people teaching them, choose whom you like.

And still, #💻┃code-beginner

To be absolutely fair, if you're learning C#, do it outside of a Unity Context and come back to Unity once you grasped the fundamentals, it'll click much much faster for you this way, else you'll probably jump from one Tutorial to the next one, hoping that they'll complete the game on their own, which they won't.

eager wagon
# stark sinew `var theObject = Instantiate(...)` `theObject.theVariable = ...` Still, pseudo-...

will simplify the question cos i think u dont underestand me.
i have a gun. the gun can create bullets. the bullet spd is a var from the gun. i want get the scr of the gun like this: public cannon cannon;
teh problem is that when i try to put the script in the unity inspector i cant (cos teh bullet is a prefab i underestand). So now this guy told me that i can modify a variable when i Instantiate the object.
the way u told me aint working for me, since when i try to TheObject.var it doesnt works

stark sinew
# eager wagon will simplify the question cos i think u dont underestand me. i have a gun. the ...

my friend, please just watch some C# tutorials, you'll thank me in the long run 🙂

It's not my job to solve your problems, it's nobodies job, it's our job to guide you towards the correct direction and give you some advice, which I did in the best possible way.
If you're going to accept it or not, that's on your side.

One more pseudo for you:

void ShootBullet()
{
  var bullet = Instantiate(...)
  bullet.speed = this.bulletSpeed
}

Tbh, IMO, you shouldn't get any more responses in THIS channel, at least take it to Beginner and admit that this is what you are.
You seemingly don't want to learn, you want us to give you the solution.

@n.navarone just stop bothering, this person doesn't want to understand, and we're wasting time and energy here

eager wagon
#

i see

#

u wont solve my problem true

#

anyways

rigid island
#

you can't just skip the basics

eager wagon
rigid island
eager wagon
#

i wached a 127 vidios tutorial before this

rigid island
#

you need a structure course,not random vids

eager wagon
#

no way

#

wont get teh solñution here

rigid island
#

the solution is you learning the basics

#

you were given a solution, because you don't understand the basics you don't understand the soltion..

robust dome
#

you just want to be spoonfed which is not ok.

#

you should learn some basic stuff first

static matrix
#

quick question:
BehindWoods = new List<GameObject>(AheadWoods);
this assigns BehindWoods to a new list and then fills the list with the contents of AheadWoods, correct?

static matrix
#

great

stark sinew
#

Yes, but I am not sure if it'll reference the original AheadWoods or if it's copying them (in case it's a reference type)

fervent furnace
#

it will not deep copy i think,
i have to check the source code

static matrix
#

ahead woods is another list

#

I think this will work

#

hopefully

fervent furnace
#

the source code....
there should be no generic solution to deep copy something

static matrix
#

what does deep copy mean?

rigid island
#

shallow copy means it copies the object but still holds the same references

static matrix
#

which means if I change the original, I will change the copy?
Or no

rigid island
#

a shallow copy would

static matrix
#

unfortunate

rigid island
static matrix
#

I can use CopyTo it looks like

#

ill figure it out

ashen yoke
#

there is also AddRange

static matrix
#

maybe
basically what im trying to do is a staggered moving of a bunch of objects

#
 WaitToMoveTarg += Time.deltaTime;
            if (!IsVis)
            {
                awaitWoodMove += Time.deltaTime;
            }
            if(WaitToMoveTarg> 8)
            {
                if (BehindWoods.Count > 0 && awaitWoodMove > 0.8f)
                {
                    var moveWood = BehindWoods[Random.Range(0, BehindWoods.Count)];
                    BehindWoods.Remove(moveWood);
                    AheadWoods.Add(moveWood);
                    MoveWood(moveWood);
                }
                else
                {
                    BehindWoods = new List<GameObject>(AheadWoods);
                    AheadWoods = new List<GameObject>();
                    Orient.transform.position = Target;
                }
            }

this is the code rn

pure cliff
static matrix
#

can one audiosource overlap with itself or does it start over if you play it again while its playing

rigid island
static matrix
#

woah
time to replace
all of play with playoneshot
no bad outcomes will come of this im sure

#

oh wait its funky and different
ill figure it out

spark yew
#

i don't really know the specific keywords/terms i have to search up to make this but how would i be able to create a circle of buttons that rotate when you cycle through them

#

like the mario and luigi system

pure cliff
spark yew
pure cliff
hasty haven
#

Is there a way I can go without allocating garbage here
meshRenderer.materials = newMaterials.ToArray();
The new material list can vary in length and id prefer to use an array + count variable
Profiler shows .ToArray() is allocating garbage

pure cliff
#

Though you'll need the ones going "back" to slerp the opposite way to the ones going "forward"

pure cliff
ashen yoke
pure cliff
#

But effectively what you need is to just know how big the array is gonna be before you start filling it and you are golden

hasty haven
#

Makes sense, that was my original approach and I just made it 256 in length but that KILLED performance super badly

#

even though I only need 3 ish elements right now

ashen yoke
#

never tried something like that, interesting

hasty haven
#

it allocated 0 garbage but was bad lol

ashen yoke
#

guess it attempts to create new submesh groups for each index

#

anyway, just do ToArray() once

#

its not garbage if it doesnt get collected

hasty haven
#

Its the only part of my code which allocates garbage every time a chunk is modified
I could switch to advanced mesh api later on probably but its performant as is

ashen yoke
#

i guess you update materials based on what voxels chunk has?

hasty haven
#

Thats what I'm doing, ill just paste the method

hasty haven
#
List<Material> newMaterials = new List<Material>();
  private void UpdateMesh() {
      thisMesh.indexFormat = IndexFormat.UInt32;
      thisMesh.Clear();
      thisMesh.subMeshCount = 0;
      colliderMesh.Clear();

      // Apply vertices
      thisMesh.SetVertices(vertexArray, 0, vertexCount);
      colliderMesh.SetVertices(colliderVertices, 0, colliderVertexCount);
      colliderMesh.SetTriangles(colliderTriangles, 0, colliderTriangleCount, 0);
      
      // Grab appropriate materials for submeshes
      newMaterials.Clear();
      for(int i=0; i<trianglePartitions.Length; i++) {
          if(trianglePartitions[i].capacity > 0) {
              thisMesh.subMeshCount++;
              newMaterials.Add(BlockDataManager.Instance.blockMaterials[(BlockType)i]);
              thisMesh.SetTriangles(triangleArray, trianglePartitions[i].start, trianglePartitions[i].DataLength(), thisMesh.subMeshCount-1, false);
          }
      }
      
      meshRenderer.materials = newMaterials.ToArray();
      thisMesh.RecalculateNormals(UnityEngine.Rendering.MeshUpdateFlags.DontValidateIndices);
      meshCollider.sharedMesh = colliderMesh;
  }
#

I have a giant array for triangles that i split into partitions

#

so each material starts at its own index and has a capacity in the triangle array, thats what the for loop is for

#

It seems like the physX calculations with mesh collider is the biggest chunk of performance now but it works fine for now

ashen yoke
#

you can completely avoid using multiple materials

#

if you use a shader tilemap shader or texture3d

hasty haven
#

Ah as opposed to using one sprite sheet and splitting the UV up?

#

I'm not using any textures right now, deciding on how i want to do things

ashen yoke
#

all cube faces have same uv

#

you "paint" them with indexed color

#

each R value 0-255 represents an index in the atlas

#

shader selects that index with frac

#

you are offseting uvs on the shader

hasty haven
#

Oh i see, i could probably do some blending between types with that as well?

#

I remember the game cube world had some pretty gradients

ashen yoke
#

with this approach blending probably wont be possible, but i havent tried

#

what do you mean by blending?

#

alternative to a single atlas is using 3d texture

#

so you select the texture from the array instead of shifting uvs on the atlas

#

also on the shader

hasty haven
#

Ah thats cool, may look into that later