#archived-code-general

1 messages ยท Page 402 of 1

ashen oyster
#

just not a dynamic one

vestal arch
#

uhh how are you setting the velocity then

#

you can't set velocity on a kinematic rigidbody

wintry crescent
ashen oyster
#

well

wintry crescent
#

Aside fron setting _jump through an event rather than inside Update(), this is exactly how I'd do stuff

ashen oyster
#

Not by changing linear velocity, I use the rigidbody's MovePosition function

ashen oyster
#

Maybe I'll just have to deal with that

wintry crescent
#

Which means you wouldn't need _jump at all

#

But that might be too much work

ashen oyster
#

Maybe

#

If this happens a lot I'll consider it though

#

Thanks for the idea

balmy plume
#

is this not working?

ashen oyster
#

It is

balmy plume
#

then why mess with it?

ashen oyster
#

You are clearly new around these parts xd

#

refactoring your code base is important

balmy plume
#

ya for code thats scattered around

sonic swan
#

i making a system for hiding behind props and the code works but when i leave the prop midair it stays there as it has no rb. but if i use rb on the prop when entering it i fall through the floor. https://paste.ofcode.org/kDxyeqkMwJce9WuwTMHHwd <-my code

arctic steeple
#

How do I see the sample rate option in Unity 6 ?

leaden ice
#

doesn't sound like a code question

balmy plume
balmy plume
sonic swan
balmy plume
sonic swan
balmy plume
sonic swan
#

im pretty sure thats not a thing

balmy plume
#

oh wait thats for 2d

#

ya wait lemme look up the doc

sonic swan
#

but its not a thing

vestal arch
balmy plume
somber nacelle
# balmy plume rb.enabled=false;

Rigidbody and Rigidbody2D inherit directly from Component so they do not have an enabled property. That is a property on Behaviour

balmy plume
somber nacelle
#

Sure, but I was not responding to any of that.

balmy plume
#

ya i am just making sure

sonic swan
balmy plume
sonic swan
#

yes but when i hide it in again and then leave the rb is already destroyed so the problem returns

sonic swan
balmy plume
#

when ur props are on ground they dont have rb to begin with right?

sonic swan
#

so do you know in cartoons like when sneaking around a person will hide behind a tree and waddle to move and stop in their place to avoid detedtion from the gaurd or whatever. im trying to remake that but the issue is when i stop hiding in the prop it remains at the position where it was left not a problem if i was on the ground but i was in the air the prop just remains the floating

sonic swan
balmy plume
sonic swan
#

exactly

balmy plume
# sonic swan exactly

same thing give air check and isIn check if (!isIn && inAir) then add rigidbody till it falls to ground then remove rb

sonic swan
#

but if i hide in the same object again and if i do the same thing again i will need the rigidbody i had just deleted to make it fall again

balmy plume
balmy plume
wintry crescent
#

is there a difference between Camera.WorldToScreenPoint and RectTransformUtility.WorldToScreenPoint?

wintry crescent
leaden ice
wintry crescent
leaden ice
wintry crescent
#

from the canvas

leaden ice
#

not sure

wintry crescent
#

or what could it be

sonic swan
wintry crescent
# leaden ice not sure

if you're not sure, then I still don't understand what the real difference is. How is one local to screen space different from another local to screen space?

leaden ice
#

there is no camera involved in that at all

wintry crescent
mossy shard
#

pls help, my pf is overreacting:

leaden ice
mossy shard
#

so, i tried to put heaps into it

#

and for some reasons it doesn't calculate my costs right

leaden ice
hexed pecan
#

What even is "pf"

mossy shard
leaden ice
#

I assume "pathfinding"? But yeah it would be nice if you were clear.

mossy shard
#

wait a sec

knotty sun
sonic swan
mossy shard
#
 public int CompareTo(Node other)
    {
        int compare = fCost.CompareTo(other.fCost);
        if (compare == 0)
        {
            compare = hCost.CompareTo(other.hCost);

        }
        return -compare;
    }
sonic swan
mossy shard
#

it doesn't compare right

#

couldn't figure out why it sets the priorities so weirdly

#

as you have seen the pic

leaden ice
mossy shard
#

so im gonna be more formal

#

i am using Astar

sonic swan
#

a* pathfiding?

mossy shard
leaden ice
#

They're using the A* algorithm, not the "A* Pathfinding" asset store asset, presumably.

mossy shard
hexed pecan
#

You can lock its rotations

#

And you can remove the rigidbody once it hits the ground if you want

#

Or make it kinematic

sonic swan
hexed pecan
#

You can ignore collisions between the player and the prop

#

And you dont need to make the prop a child of the player, you can just move it manually

sonic swan
hexed pecan
#

Show a video of the issue?

hexed pecan
#

Show what you tried also

sonic swan
leaden ice
#

presumably the teleportation of the object into a degenerate position like inside some other collider(s)

hexed pecan
#

gameObject.transform.position = ... is definitely problematic, yes

sonic swan
#

so im disabling the players colliders , so the active rb uses the collider of the prop which is a child of the player . this is great but if i make the prop have a rigidbody the player rb now isnt using the box collider so it falls trough into the ground and since the box collider is a child it falls with it

balmy plume
#

disable the prop's colliders

#

instead

sonic swan
#

then i cant walk by enemies which is the entire point of the system

hexed pecan
balmy plume
sonic swan
#

props and enemies dont collide already

sonic swan
hexed pecan
balmy plume
#

thats the point of the layer

hexed pecan
#

With prop layer* or prop collider.

sonic swan
balmy plume
#

i believe its physics2d.detectCollisions=false; for 2d stuff

hexed pecan
#

You don't want to disable all collisions.

sonic swan
#

yes

balmy plume
#

right better to use ignore collions with layermask

hexed pecan
#

Also FYI, there is a separate collision matrix for 2D and 3D

sonic swan
#

also how do i make it not ignore collsions again

wintry crescent
#

I'm overriding ScrollRect. How do I get my variables to show up in the inspector? Bonus points if I don't have to make a custom inspector ๐Ÿ˜ญ

#

my AnchorPoint doesn't appear in the editor, it's only the ScrollRect stuff

thin aurora
#

Oops, misread

somber nacelle
#

ScrollRect likely has a custom inspector so you'll need to write your own for SnapScrollRect

wintry crescent
somber nacelle
#

there's always debug mode in the inspector which shouldn't use the ScrollRect's custom inspector, but that comes with its own drawbacks

wintry crescent
#

custom inspector it is, ugh

somber nacelle
#

does that need to inherit from ScrollRect? if not, then you can just make it a separate component that controls stuff on th ScrollRect. then you wouldn't need a custom inspector for it

obsidian anchor
#

I'm currently having an issue with this SimpleRotator script in JetBrains, as the software won't autofill the coding prompts, any advice?

somber nacelle
#

!ide

tawny elkBOT
obsidian anchor
somber nacelle
#

great, so that's one step

obsidian anchor
wintry crescent
somber nacelle
#

why

somber nacelle
obsidian anchor
wintry crescent
# somber nacelle why

because it's directly manipulating the ScrollRect behaviour, I'm making a ScrollRect that snaps to indifidual elements inside it

obsidian anchor
somber nacelle
somber nacelle
wintry crescent
somber nacelle
#

that's literally step 4 in the guide that was linked

obsidian anchor
somber nacelle
#

i mean, clearly not.

#

we don't need the reaction images here, thanks

sleek bough
#

@obsidian anchor ^^

supple hawk
#

Unity's Input System and detecting when the button is no longer pressed.

obsidian anchor
delicate oak
#

Has anyone made a card/effect stacking game before? Im trying to find a practical example online I can use to guide my sorta design philosophy in making this project.

Essentially I am making a game about comboing effects from a large list of possible effects. And managing interactions between those has been sort of hectic. Same design problem games like the binding of isaac and whatnot likely face. Like ill have an effect that generates 10 projectiles. But then if those projectiles gain an onhit effect, or a traveltime effect. Id then have to manage that interaction somewhere. Currently I just have a long list of super abritrary stats that I modify, but I doubt this is sorta the philosphy that other designs would use as its unruly with just 15 abritrary stats I can read.

So yeah, rambly message aside, does anyone have a good open source practical example of a game that handles stacking multiple effects and handing interaction between a large set of these effects. IE like the binding of isaac, or really any card game as well. Even games like vampire survivors likely manage a similar problem at a smaller scale. Im hoping the standard solution isnt just going in and hardcoding things that dont stack quite well. As that would feel awful lol

heady iris
#

This is a very common problem

#

I also don't have a great answer, haha

delicate oak
#

I play so many games that do these things that Im hoping theres a solid like, design principle out there

#

theres no way TBOI is spaghetti code

heady iris
#

spaghetti code is more common than you might think (:

latent latch
#

the secret is composition

#

oop is a trap for this type of stuff

maiden stone
#

How might I recursively iterate through a chain of game objects in a specific direction?
I'm trying to create gears which turn each other, however this requires me to have a drive gear and a driven gear. My current method of checking what gears are touching each other is using Physics.OverlapSphere. Currently I go through a for loop of all adjacent gears and set the colliding gears to the drive's inverse, although my issue is defining which one is the drive.

I have a stupid little fix which makes it work for two gears only, which is having a bool called driver, however this wont work for a chain of gears.

here's my update method if anyone else can give me any ideas on how I can fix my issues.

    void Update()
    {
        transform.Rotate(rotation * Time.deltaTime * force);
        Collider[] hitColliders = Physics.OverlapSphere(transform.position, radius);
        foreach (var hitCollider in hitColliders)
        {
            if (hitCollider.GetComponent<CapsuleCollider>() != GetComponent<CapsuleCollider>()) // Doesnt collide with itself
                if (hitCollider.GetComponent<Gear>()) // If the part is a gear
                {
                    Debug.Log("Colliding with a gear");
                    Gear drivenGear = hitCollider.GetComponent<Gear>();
                    if(driver) drivenGear.calculateRotation(force);
                }
        }
    }
latent latch
#

Assuming you just don't want to proliferate the values, you're probably looking for the tail of the gears that's dictating the direction of all gears if I'm understanding this correctly.

#

Unless you don't have like a list that's predefined of all the gears, you're probably populating all the gears to some manager and resolving it all from there.

#

so it's a question of resolving sets with other sets of gears

leaden ice
maiden stone
maiden stone
leaden ice
#

then you end up with a graph structure

#

and you can do all the normal graph algorithms like DFS to find the connected ones

latent latch
#

sounds like a fun problem

maiden stone
#

I'm still kind of confused. I should have a manager which this is all put into which will then run it through a graph algorithm? I'm going to assume the DFS can handle my issue of the driven gear controlling the driver? I haven't worked with graph algorithms much, but I'll definetly look into it

#

I should probably research graph theory a bit more lol

latent latch
#

I'd probably make the gear object contain a list of other gears it's connected to in the moving direction

#

Rather, other gears that this gear is applying the force to

maiden stone
#

yeah thats what I currently have I believe?

latent latch
#

Probably fine honestly if you don't care about keeping track of the set

maiden stone
#

im thinking i can just call the method of the next gear with the driver as an input, then the method controls the connected gears and so on, ignoring the driver. Do you think that would work?

#

I know I should probably do the graph way, Its just kind of confusing me

latent latch
#

Doing it recursively is fine, as long as no two gears can act upon the same gear. My only concern is the amount of physic queries you're doing if you do have multiple gears.

#

Maybe better off using Trigger events over querying every frame

maiden stone
#

Alright

latent latch
#

they also offer events for when they stop intersecting so that would be helpful

maiden stone
#

okay

spare dome
latent latch
#

Do you have an extra bracket there

spare dome
#

I do not

quartz folio
#

It looks like those are enum literals

#

Not variables

latent latch
#

If line 51 is entering, I don't see why 55 wouldnt

quartz folio
#

But you've not shown the source for LocalTeam

spare dome
#

yep will do that now

quartz folio
#

So you're just comparing if 0 == 1 in that if statement

#

What's the point of it

#

What's the point of either of those if statements

spare dome
latent latch
#

oh yeah you're casting the enums

quartz folio
#

Surely you want to compare Teams with the literal

#

(Preferably using a switch)

spare dome
#

ah yeah I could use a switch statement, give me a second

toxic vault
#

I am trying to add controller support for my game, and also allow it to be played on the Steamdeck. Not only would I need to allow the controller joysticks and buttons to work for my player movement, aiming, shooting, but even for the GUI navigation in main menu, character selection, using dropdowns for display resolution, checkboxes etc.

Would you use using the new input system is easy to do this? Or you recommend something like Rewired?

somber nacelle
#

yes, the input system is designed to be fairly easy to implement support for different input types. check the documentation pinned in #๐Ÿ–ฑ๏ธโ”ƒinput-system to learn how to use it

toxic vault
steady moat
# delicate oak Has anyone made a card/effect stacking game before? Im trying to find a practica...

Composition.

//Simple
public class Projectile : MonoBehaviour 
{
    private List<Effect> effects; 
    
    ...
    
    public void Initialize(IEnumerable<Effect> effects) 
    {
        this.effects = effects.ToList();
    }

    public void OnHit()
    {
        //Invoke OnHitEffect
    }
}

public abstract class Effect {}

public class OnHitEffect : Effect {}

//MoreComplex
public class Projectile : MonoBehaviour 
{
    [SerializeReference] private List<ProjectileBehaviour> behaviours; 
    private List<Effect> effects;
    
    ...
    
    public void Initialize(IEnumerable<Effect> effects) 
    {
        this.effects = effects.ToList();
    }

    private void Update()
    {
      foreach(ProjectileBehaviour behaviour in behaviours)
        behaviour.Update();
    }
}

[Serializable]
public abstract class ProjectileBehaviour {}

[Serializable]
public class ImpactProjectileBehaviour 
{
  public virtual void Update()
  {
      //Impact Logic.
      //Access projectile effects
  }
}

sharp temple
#

Hey I need help i cant figure out how to build a navmesh at runtime

#

I have the latest navigation ai package (1.1.5) yet i dont have an assembly reference to NavMeshSurface ?

#

I watched multiple videos but they were all outdated

#

I am on unity 2022.3.16f1

#

Even with the navmeshcomponents package on github it doesnt work

#

Like I cant put a navmeshsurface as a navmeshsurface variable

flat abyss
#

Hello everyone! How can I get ALL the tiles in a tilemap? I've been trying to add some overlay tiles in random spots taken from the floor tiles but I'm having some difficulties

#
    {
        return list.OrderBy(x => Random.value).Take(count).ToList();
    }
    
    [Button]
    public void Run(){
        cells = new List<Vector3Int>();
        
        //floorTiles.CompressBounds();
            BoundsInt bounds = floorTiles.cellBounds;
            TileBase[] allTiles = floorTiles.GetTilesBlock(bounds);
        for (int x = bounds.min.x; x < bounds.max.x; x++)
        {
            for (int y = bounds.min.y; y < bounds.max.y; y++){
                    TileBase tile = allTiles[x + y * bounds.size.x];
                    if (tile != null) {
                        cells.Add(new Vector3Int(x, y, 0));
                        Debug.Log("x:" + x + " y:" + y);
                    }
                }
            }
        int randa = Random.Range(3,10);
        randCells = GetRandomItems(cells, randa);
        foreach (Vector3Int t in randCells){
            overlayTiles.SetTile(t, chest);
        }
        
    }```
#

That's the code I came up with, but it gives me an error about index is outside the bounds

rotund perch
#

how important is putting the private namespace?

hexed pecan
#

private is an access modifier, not a namespace

#

In C# things are private by default so it's just a style choice

rotund perch
#

oh I kinda don't really know what all the terms like namespace actually mean

#

It seemed like it kinda made sense

rigid island
# rotund perch oh I kinda don't really know what all the terms like namespace actually mean
leaden ice
delicate oak
compact spire
#

Can you "overuse" monobehaviors for UI elements?

cold parrot
compact spire
#

lose a bit of seperation and have the parent class (monobehavior) make calls into the class constantly.

#

I guess in this sense it's not a UI element, more of a runtime editor

#

The class is for showing and validating placement of blocks

latent latch
#

And, probably a pipeline for these groups for which should come first if needed.

cold parrot
compact spire
#

I'm just trying to have clear seperation of my classes, but dependencies are making that difficult.

cold parrot
#

what does separation mean to you? and why do you want it?

compact spire
#

Well I had a class that did many different things, and it became unmanageable. So I'm seperating it out based on the states of my state machine so it's clearer what they do.

cold parrot
#

the code will likely be just as unmanageable (maybe more so) if you just spread it out, thats not getting fixed by making more classes. Its a structural/modelling issue in most cases.

#

what would improve maintenance is potentially abstraction, followed by separation.

#

but since you're dealing with a state machine complexity issue, for that to be successfull you would have to primarily separate transition rules from state implementation.

compact spire
#

I think I hvae that, I'm just trying to keep it lol

#

I mapped it out

#

Before I started making changes the state machine just called into an assembler class which everything under this was a apart of (except the gizmo subclasses)

#

I could still put another class inbetween the state machine and the other classes that holds the selected object and the grid and pass them through on method calls for normal classes and events for monobehaviors?

#

@cold parrot ?

#

ahh bummer, well if I continue to stare at it long enough I might come to a solution.

rotund perch
#

what's going on here? I don't remember making this script

leaden ice
#

Oops sorry about caps lock

rotund perch
#

that scared me for a bit lol

leaden ice
#

Anyway - like it says - you are using the StandaloneInputModule still

#

you need to upgrade it to the input system input module

#

Select your event system object and click the button on the input module to switch it.

rotund perch
#

Oh I didn't realize the new event systems would be different than my other one

leaden ice
#

the event system is the same

#

the input module changes

rotund perch
#

anyway that worked, thanks!

#

oh yeah

radiant oasis
#

hi, how should i properly take an object from an array and use it as a target for a navmesh agent? i have a script to detect targets in front of the agent and add them to an array as visible targets. my enemyAI script takes that array and turns it into the target for the navmesh agent. it works like it's supposed to but whenever the player leaves the agent's field of view it starts throwing up index errors. i followed a tutorial from sebastian lague for the vision cone. i added the hasTarget bools trying to find a workaround to the errors but they haven't worked. the specific error says ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

leaden ice
#

As for where the actual error is happening you would need to check the line number and filename from the error

#

every exception will have a line number and a filename

#

you need to look there

radiant oasis
#
  1.       target = fov.visibleTargets[0];
    

it's this one specifically. (and the ChasePlayer() function in Update) the player gameobject is the only thing in the array when so when it leaves vision the array becomes empty.

leaden ice
#

you cannot access index 0 (the first element) of an array or list with 0 elements in it

#

Sounds to me like hasTarget should not be a separate variable at all. It should just be a property that checks if there are any items in the visibleTargets list. For example:

public bool hasTarget => visibleTargets.Count > 0;```
#

it shouldn't be a separate variable that you set (incorrectly in this case)

radiant oasis
#

okay let me tinker with that and i see if i can get it working, thank you!

leaden ice
#

it seems like hasTarget has been set to true improperly, since there are no visible targets

radiant oasis
#

yeah, that much i had understood. i just couldn't figure out how to get around it

leaden ice
#

and you are trying to read element 0 from the list, which has no elements.

leaden ice
radiant oasis
#

it works now, thank you!

radiant oasis
alpine pagoda
#

Yo I've been having some trouble, I have an prefab which is an empty object with a few scripts in it and then a 2D sprite as a child. I have a manager that is supposed to spawn in this prefab and set its parent to a specific canvas so it is visible to the players, its currently not working as it copies the prefab but has the parent of it null, making it clone outside of the canvas, does anyone know how to help? Here's the script ```using UnityEngine;
using System.Collections.Generic;

public class MilitaryManager : MonoBehaviour
{
public GameObject militaryPrefab;
public Transform stagingArea;
public List<GameObject> ownedUnits = new List<GameObject>();
public Canvas canvas;

public void PurchaseUnit()
{
    GameObject newUnit = Instantiate(militaryPrefab, stagingArea.position, Quaternion.identity);

    newUnit.transform.SetParent(canvas.transform, false); 
    ownedUnits.Add(newUnit); 
}

}

leaden ice
leaden ice
#

you should just be doing GameObject newUnit = Instantiate(canvas.transform);

#

that's the right way to spawn any ui prefab

#

although I imagine you would actually want a better parent than the canvas itself - usually a panel or something.

alpine pagoda
flat abyss
#

Is it me or while doesn't work in Unity 2022?

mellow sigil
#

it's you

flat abyss
#

Well I'm going crazy because while really doesn't seem to work. It's completely skipped.

quartz folio
#

Break out the debugger and look closer

#

Because these questions are so easily interrogated

leaden ice
thin aurora
#

If you want help, share the !code

tawny elkBOT
cold parrot
# compact spire I could still put another class inbetween the state machine and the other classe...

As a baseline I donโ€™t see much reason why you would need any separation into classes here. I would think about why any piece of code would maybe have to change in the future and try to isolate the rest of the system from those changes (within reason). Typically these have boundaries along input/control/presentation/view/feature and other concerns specific to the project. This doesnโ€™t necessarily mean making more classes, it could be methods, blocks inside a method, groups of fields, context structs, states, named signals etc. Additional classes/interfaces would only happen when additional instances are required because of composition, I.e. one thing/service being multiple things to different clients; or for technical reasons derived from the way Unity works. Gratuitous separation where you canโ€™t really explain why the separation is necessary leads to low cohesion and unnecessary API surface area that can be misused/misunderstood in the future.

simple stump
#

Hey you guys, is peer-to-peer difficult to implement in a card game?

mossy shard
#

can unity crash cause of an infinite loop?

loud heath
#

Could anyone give me insight to make my code work, it's not counting to 5 seconds, instead it's skipping the if statement and deleting the game object right away.

flint pilot
worldly stirrup
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
using System.Linq;
[CreateAssetMenu]
public class ruleTileCombine : RuleTile<ruleTileCombine.Neighbor> {
    public bool alwaysConnect;
    public bool isWallRun;
    public TileBase[] tilesToConnect;
    public bool checkSelf = true;
    public class Neighbor : RuleTile.TilingRule.Neighbor {
        public const int Any = 3;
        public const int Specified = 4;
        public const int Nothing = 5;
    }

    public override bool RuleMatch(int neighbor, TileBase tile) {
        switch (neighbor) {
            case Neighbor.This: return checkThis(tile);
            case Neighbor.NotThis: return checkNot(tile);
            case Neighbor.Any: return checkAny(tile);
            case Neighbor.Specified: return checkSpecific(tile);
            case Neighbor.Nothing: return checkNull(tile);
        }
        return base.RuleMatch(neighbor, tile);
    }
    bool checkThis(TileBase tile)
    {

        if (!alwaysConnect) return tile == this;
        else return tilesToConnect.Contains(tile) || tile == this;

    }

    bool checkNot(TileBase tile)
    {
        if (!alwaysConnect) return tile != this;
        else return !tilesToConnect.Contains(tile) && tile != this;
    }
    bool checkAny(TileBase tile)
    {
        if (checkSelf) return tile != null;
        else return tile != null && tile != this;
    }
    bool checkSpecific(TileBase tile)
    {
        return tilesToConnect.Contains(tile);

    }
    bool checkNull(TileBase tile)
    {
        return tile == null;
    }
}```
#

This is my custom rule tile script to make different rule tiles connect and work with each other. I'm trying to make a rule override tile for the tiles that use this script, but it doesn't seem to work.

dusky pebble
#

Need help with player respawn when falling off platform in Unity - Zip file attached

Hi everyone,

I'm currently working on a Unity project and I'm facing an issue with player respawn. My goal is to have the player respawn at the initial spawn point when they fall off the platform.

I have tried several approaches, but nothing seems to be working as expected. I've attached the entire project (without the Library folder to reduce size), including all necessary scripts and assets, in a ZIP file for reference.

Here's the problem:

When the player falls off the platform, they should respawn at a designated spawn point.
The platform and player are set up, but the respawn logic doesn't seem to work correctly.
I would really appreciate it if someone could take a look at the project and help me identify what might be going wrong.

Thanks in advance!

worldly stirrup
thin aurora
#

If you want players to respawn when falling out of bounds, I suggest placing a big plane at the bottom to catch players and have them respawn. Alternatively, hardcode a base Z position that when players go below respawns them

soft shard
worldly stirrup
#

I'm also open for other ways to use the same rule tile pattern for different sprite sets

soft shard
# loud heath Could anyone give me insight to make my code work, it's not counting to 5 second...

Its not clear where that function is being called or when you are resetting your timer variable, though in general, you can use Time.time with a variable and calculate the difference - as Unknown mentioned, if you want the delete to happen after your timer, youd want it to happen inside your if-statement, for example:

float someTime = 0f;

void SomeFunc()
{
if(someTime > Time.time) {someTime = Time.time + 5f; DoTheThing();} //every 5 seconds, "TheThing" will be called
}

In that example, DoTheThing would represent your log and destroy logic, if you stick with the code you have, youll want to make sure you also reset your timer after it does "the thing"

worldly stirrup
dusky pebble
# thin aurora If you want players to respawn when falling out of bounds, I suggest placing a b...

Thank you for the suggestion! I tried using the plane at the bottom to catch the players, but it didn't work as expected. The problem seems to be that the character is not being teleported to the starting position. Additionally, I have already tried the hardcoding idea, but I didn't have success with that either. Any suggestions on what I can check to fix this? I am using the Kinematic Character Controller, which I think might be interfering, but I don't have much experience with Unity.

thin aurora
#

I'm not too familiar with Kinematic but I believe it ignored actual collissions?

#

Regardless hardcoding should work and seems most reasonable. If it didn't work I suggest sharing the related !code

tawny elkBOT
soft shard
# dusky pebble Thank you for the suggestion! I tried using the plane at the bottom to catch the...

Since falling is usually only a change in the y-axis, you could setup a check with the transform instead, for example if(player.transform.position.y > 25) {Respawn();} - if your respawn logic happens in a different script, you could setup an event and pass your player as a param to have your respawner know when to hard-set the position of your player transform (and if you cant override the player transform because of the asset your using for your character, that asset may have some API that sets the position instead), this way you dont have to rely on physics and colliders (although as Fused mentioned, seeing your scripts setup on a paste site may help)

dusky pebble
# soft shard Since falling is usually only a change in the y-axis, you could setup a check wi...

I've tried several ways to solve the problems I've encountered, but I'm just getting more confused with each attempt. Since things are getting complicated, I've decided to try a different approach. I'm going to create a new project, but this time without using Kinematic on the Rigidbody, to see if I can simplify the movement and platform mechanics.

I hope this will help me better understand how the components are interacting and avoid some of the errors I've been facing. I'll update you with my progress as soon as I make more headway.

Thanks for your patience!

sharp temple
knotty sun
tawny elkBOT
mossy shard
#

in a loop, which would be more efficient, iterating trough 8 elements each time in the loop or making a bool with Physics.OverlapCircle? I don't know how overlapCircle operates so idk which would be faster

narrow monolith
#

hello guys when i click my script and its supossed to take me to my script in visual studio it show nothing how do i fix that

wheat spruce
#

even if you used a very slow function, the actual impact it would have is negligible

#

now if you had 8,000,000,000 elements, thats a different story

#

consider a function taking 100nanoseconds, vs 1nanosecond. Sure its 100 times as slow, and that would matter if you're writing very advanced code where performance is incredibly vital.
Then consider that in the time it takes you to blink, the 100ns function could be called 10 million times

cursive granite
#

hey, how do I reference gameobjects from a different scene in the editor?
I have Scene A (The player starts there) and Scene B
When I switch to Scene B the player is a DDOL object
Scene B has gameObjects with scripts, that need to reference to the player. But I can't select them in the editor as the Player is in a different scene

#

I am pretty sure there has to be a solution to handle these types of situations, but I just couldnt find anything useful right now

robust dome
#

DontDestroyOnLoad is what you are probably looking for

cursive granite
#

Yes, my player is a DontDerstroyOnLoad object, but in the editor I can not reference him as he is in a different scene

#

Basically the player has the PlayerHealth script attached to him, which I am trying to acces in Scene B with a DealDamage script

steady bobcat
cursive granite
#

I haven't really decided on how the damage is being dealt yet, I just have a simple debug object for it as of now.
Interacting with it will Damage the player.
In the future, I would probably plan it via triggers? My plan is to make it check weather I was hit by any objects (bullets, bottles, lego bricks or whatever)

steady bobcat
#

A common design is using an interface to make a generic interaction system that many scripts can utilize (e.g IInteractable)

cursive granite
#

give me a sec so I will be able to provide further information that might help

wheat spruce
#

What would cause visual studio to be unable to detect certain errors, yet still show others?

public struct Rectangle
{
...
...
public static int Padding => 5;
}```Like in my Rectangle, various classes access the Padding property. Commenting it out, Unity correctly detects the error, yet Visual Studio does not
#

its not like VS isnt able to detect any error

steady bobcat
#

!ide

tawny elkBOT
wheat spruce
steady bobcat
#

only explanation for it not giving correct intellisense info/errors

#

if the script is opened correctly VS opens the generated .sln and understands the project

wheat spruce
#

visual studio has no problem with actually making use of Unity

steady bobcat
#

clearly not if you say it fails to show errors correctly

#

if its not opened correctly it can give generic c# syntax errors but nothing more complex relating to the whole project

wheat spruce
#

well for here, the padding property doesnt exist

steady bobcat
#

can you do "Find all references?" @wheat spruce

wheat spruce
steady bobcat
#

then vs is not working as it should

wheat spruce
#

also, neither my Grid or Rectangle have any relavence to unity, only that theyre using the Vectors that unity provides

cursive granite
# cursive granite give me a sec so I will be able to provide further information that might help

Interactable Objects script:

public class basicinteractableObject : Interactable
{
protected override void Interact()
{
//do stuff
}
}

PlayerInteract script:

public class PlayerInteract : MonoBehaviour
{
private float distance = 3f; //raycast length
private LayerMask mask;
private PlayerUI playerUI;
private InputManager inputManager;

void Start()
{
    playerUI = GetComponent<PlayerUI>();
    inputManager = GetComponent<InputManager>();
}

void Update()
{
    playerUI.UpdateText(string.Empty);
    Ray ray = new Ray(cam.transform.position, cam.transform.forward);
    Debug.DrawRay(ray.origin, ray.direction * distance);
    RaycastHit hitInfo;

    if (Physics.Raycast(ray, out hitInfo, distance, mask))
    {
        Interactable interactable = hitInfo.collider.GetComponent<Interactable>(); 
        if (interactable != null)   
        {
            playerUI.UpdateText(interactable.promptMessage);
            if (inputManager.onFoot.Interact.triggered)
            {
                interactable.BaseInteract();  
            }
}
#

I left out some parts of the script that are not important to the core functionality

rain minnow
steady bobcat
wheat spruce
steady bobcat
wheat spruce
#

wheres the button to regenerate the solution?

steady bobcat
#

Right by where you can configure the code editor

#

hell you can even open the .SLN in the project yourself and see what it does

rain minnow
wheat spruce
cursive granite
#

pass data from scenes

steady bobcat
#

IN UNITY

wheat spruce
#

oh

#

then yes, there is the solution file

knotty sun
steady bobcat
#

check these

wheat spruce
#

yeah, its the same for me

steady bobcat
#

also make sure this package is updated (if not there use a newer unity version)

wheat spruce
#

already did

#

also when you press the regenerate button, does it do it instantly?

#

I can press it over and over again, it doesnt make anything appear

knotty sun
# wheat spruce already did
  1. Close project and VS
  2. Go to project folder in File Explorer
  3. Delete .sln amd .csproj files
  4. Open Project
  5. From Unity open C# project
  6. Screenshot VS Window
steady bobcat
#

something in your VS must be miss configured or outdated then ๐Ÿค” Is it VS 2022?

knotty sun
#

nope

wheat spruce
#

I did the steps

#

this is step 6

knotty sun
#

no way Assembly-CSharp-Editor.csproj is a sub element of Assembly-CSharp.csproj

steady bobcat
#

no its the "show all files" view

#

toggle this

wheat spruce
steady bobcat
#

this looks fine actually which is strange, can you find references for your Property now?

wheat spruce
#

let me open a non-unityt project, want to check if the csproj and sln files show up without showing all files

#

Im doubting whether they do typically show up for me

#

yeah, sln is always hidden

wheat spruce
#

which makes no sense because it absolutely should be producing errors

#

its not like it makes it impossible to actually work without VS creating 100% of the errors it should

#

it just makes it damn slow to work

steady bobcat
#

If you modify your VS installation does it have the unity tools?

wheat spruce
steady bobcat
#

wtf is wrong with it ๐Ÿ˜

wheat spruce
#

the VS installer was the first thing I checked

#

all up to date, unity tools are there

spare dome
#

maybe reinstall VS?

#

If it is borked, that may be your only option

wheat spruce
#

and im almost out of options

#

doubt its the issue, but I do have 3 versions

#

and also visual studio code

spare dome
#

try a different version of VS

#

just another thing to check

wheat spruce
#

whats strange is ive only noticed this occur as of late, its never done this in my non unity C# work

spare dome
#

VS is a bit grumpy today

#

gotta whip it back into shape

wheat spruce
#

and I only switched back to unity a few months ago, so for all I know its always been borked since I moved back, but I never noticed it until now

#

fuck it, im uninstalling every single IDE

#

I really hope it fixes it, cause what is there to do if thats not the case

spare dome
#

nothing good, thats what

wheat spruce
#

well, I'll know in 2 hours once it finishes uninstalling

kind willow
#

Is there a build in way to make an UI sprite being tiled only by one axis?
If not, what is the easiest workaround? Cause I ve found one, calculating needed pixel per unit multiplier each time resolution updates, but it's lame

odd plank
#

https://pastebin.com/4ueKvFVF

I am working with this Helicopter script, its a tiny example from the asset store. I have found two "issues" that I am going to work on resolving. And I've put TODO comments on the two sections of the script I believe where to focus on these two issues.

  1. When you land the helicopter on a higher elevation of the terrain, it requires more EngineForce to "lift off".
    This happens in LiftProcess, and I believe the issue here is taking the raw value of HelicopterModel.Y, instead of the difference between the Ground and the Helicopter?

  2. When I switched to my models, Synty which are much larger in scale, and then later resize the Capsule Collider to fit within the model, and two Box Colliders for the "feet" (but unsure if they affect this), the "360 turn" on E/Q buttons, is much slower.
    Now this one, I don't fully understand just yet. The script uses HelicopterModel.AddRelativeTorque, so my assumption is the capsule collider affects the physics... Though not sure why a longer one didn't have the opposite affect, but I also don't know where the pivot point is on these calls yet.

#

Now I understand, within the script as is. I just need to increase the variables for the Forces exposed. But Id like the actually understand more what is happening, so its not just "magic numbers" I am randomly setting.

wheat spruce
#

I just cant get my head around why it wouldnt show such a plain and simple error

odd plank
#

Trying to get a configuration comparison .. sadly I am still understanding how the colliders affects the physics, so I size them properly as well.

wheat spruce
#

reinstalled

#

deleted the sln and csproj files in advance

#

๐Ÿคฌ

#

wait a second, opening up those files makes the errors appear

#

but then uncommenting the property, unity doesnt show the errors, but VS doesnt update to clear them

#

it almost seems like VS somehow isnt scanning the solution correctly

#

it only shows errors up once i actually interact with a file

somber nacelle
#

Have you regenerated the project files

wheat spruce
#

yeah

#

before I opened unity back up, I deleted the .sln and .csproj files first

#

then the regenerate button

#

at least it is showing the errors it was meant to now

#

just that VS somehow isnt scanning the entire solution to find all the errors until I nudge it

#

ill see if I can get help elsewhere, it doesnt seem like its a unity problem

#

I might have solved it

#

this was set to current document

#

what a pain notlikethis

wintry crescent
#

When referencing a text component made using text mesh pro, is there a reason why would I ever use TMP_Text over TextMeshProUGUI?

#

or vice versa? I've always been using TMP_Text but the project I'm working on seems to have a mix of both and we should probably standardise on something, but I'm not sure on what

leaden ice
#

that makes your script more versatile

#

Unless you are using some feature that is specific only to the UI version, I recommend always using TMP_Text

wintry crescent
leaden ice
wintry crescent
#

geniunely didn't know it existed

leaden ice
#

TMP_Text can hold references to both TextMeshPro and TextMeshProUGUI

leaden ice
#

even though it's kind of the reason the asset is named TextMeshPro

#

Unity has a 3D text component called TextMesh

#

TextMeshPro is the "improved" version of it

#

and hey they have a GUI version called TextMeshProUGUI too

wintry crescent
#

TMP documentation is so unhelpful, wtf...

#

I'll definitely check it out, that's pretty cool

latent latch
#

they're pretty arse but sometimes you get lucky and there's a line of documentation

heady iris
#

seeing TextMesh finally made me understand why MeshFilter exists

#

both of them can provide a mesh to a renderer!

#

great doc string

#

mildly scary: why is there a RequireComponent(typeof(Transform)) in there

#

๐Ÿค”

leaden ice
#

That code was probably incredibly old

#

they might not have always thought of Transforms being guaranteed on GameObjects at the time.

heady iris
#

yeah

#

thus transform surviving when, say, light did not

#

cowards. every game object should have a light on it.

jaunty sleet
#

Does anyone know how to get the unity newtonsoft package imported? I heard unity added it in as an official unity package but I haven't been able to get it to show up in the unity registry when I search for it even though I updated to the latest version of unity

sleek bough
jaunty sleet
sleek bough
jaunty sleet
wintry crescent
#

Is there a nice way to get a callback when the number of children on an object changes?

#

it's a ui element (so with a recttransform) if that helps

latent latch
cold parrot
jaunty sleet
wintry crescent
somber nacelle
latent latch
#

Actually not sure if those work with UI, assuming Transform implies recttransform too

#

but Anikki may have the better answer if so

somber nacelle
#

RectTransform inherits Transform so it should work

spare dome
jaunty sleet
somber nacelle
#

are you seeing the error only in your IDE? or does it appear in the unity console when you save too?

cold parrot
jaunty sleet
somber nacelle
#

go back and reread my first reply to you

jaunty sleet
wintry crescent
#

but I found a different solution, so nevermind

cold parrot
latent latch
#

they're pretty barebones as they are anyway

wintry crescent
cold parrot
#

too bad you havenโ€™t told us what that is, x/y problem and all that.

dire bramble
#

Phidgets with Unity

jaunty sleet
#

anybody know it it's possible to get a reference to an instance into an editor script? I haven't been able to figure out how to do it while the game is not in runtime but I need the reference for the behavior of the editor script

somber nacelle
jaunty sleet
# somber nacelle <:itdepends:1108023708695662672> can you be more specific about what exactly yo...

I have a series of nodes and I have a pathfinding algorithm that depends on which nodes are connected, which I am going to be doing manually as I make the map for my game. So I am making a script to let me easily choose the connections by using handles in an editor script and saving the connections in a json file. I represent the node positions using game objects which are all children of a main game object, which allows me to get the list by retrieving all children of the object. I need a reference to this object in my editor script in order to place buttons on all unselected nodes, which I can then click to add a connection between the selected and clicked node

somber nacelle
# jaunty sleet I have a series of nodes and I have a pathfinding algorithm that depends on whic...

well you have a few options, there are obviously the Find methods which aren't really ideal but definitely work, you could trigger whatever this directly from the instance of some component on that object which would allow you to just pass the reference (you would wrap this in conditional compile symbols so it isn't compiled into the build to avoid build errors), have an editor window that you directly assign the reference in. there are likely other ways and you'd probably have to ask in #โ†•๏ธโ”ƒeditor-extensions for any other suggestions if these don't work out for whatever reason

jaunty sleet
#

if I ever finish and build it I could actually take this whole part of the code out and just put the final json file in

soft escarp
#

is it a good idea to apply slope movement to everything? i mean it activates only on angled surfaces but replacing the ground movement with slope movement saves some space

heady iris
#

Flat ground is simply a slope of zero degrees (:

#

It seems reasonable to me.

#

In fact, that seems like a great idea to me; it means that movement on various floor types will be more consistent

spare dome
#

Is the type var a broad type that can be used for specifying any type?

#

I have never used it and I have encountered an area of which is may be useful (in this case I'm using it to get a tuple from a function of mine to return multiple items)

latent latch
#

var is fake. c# is a strongly type language so the compiler knows the type of it anyway, what you'd be doing is denying yourself clear code

spare dome
#

so it's best not to use it?

latent latch
#

unless you don't want to type out a large dictionary typing, no

#

as in no, avoid it ;P

spare dome
#

alrighty thanks for the insight

latent latch
#

it's more of a thing for dynamic languages when you care less for the type at the time

#

but in reality, web devs are lazy

rough hornet
#

You have to use var with anonymous types but not as likely to be using those in unity i believe.

rotund perch
#

@heady iris so let me see if I can understand this properly

In Identifiable Processor:

        private static void OnWillCreateAsset(string path)
        {
            EditorApplication.delayCall += () => HandleAsset(path);
        }

        private static void HandleAsset(string path)
        {
            if (typeof(Identifiable).IsAssignableFrom(AssetDatabase.GetMainAssetTypeAtPath(path)))
            {
                var identifiable = AssetDatabase.LoadAssetAtPath<Identifiable>(path);
                identifiable.ConfigureGuid();
                EditorUtility.SetDirty(identifiable);
                AssetDatabase.SaveAssetIfDirty(identifiable);
            }
        }

this section basically, when the Identifiable script is added to a gameObject, will generate a GUID for it? And the GUID is generated based on the path, but what it's based on doesn't really matter a ton it matters what the GUID is? And it's based on the path because then there's no off chance that there's a duplicate GUID?

#

What's the significance of Identifiable being an abstract class, what is that?

#

I'm also wondering how you find what object corresponds with the GUID

heady iris
#

The GUID is not generated by the IdentifiableProcessor. All it does is load the asset and tell it to grab its own GUID

rotund perch
#

yeah

heady iris
#

Identifiable has the actual logic to grab the GUID from the asset database

heady iris
#

By itself, it isn't meaningful, and you can't instantiate it

heady iris
#

for others, I'll find them all through a more elaborate means

#

e.g. I have a tree of "settings" objects

willow kestrel
#

public class DeleteOnClick : MonoBehaviour
{
    void OnMouseDown()
    {
        Transform parent = transform.parent;
        Destroy(gameObject);

        if (parent != null && parent.childCount == 1)
        {
            Destroy(parent.gameObject);
        }
    }
}

I used this for my block destroying system script but when I break the block it leaves an invisible hitbox leftover, why

heady iris
#

I walk that tree to find all of my settings and put them in a big dictionary

#

In your case, I presume you already have a list of prefabs you can use somewhere

#

Just look through that (maybe build a Dictionary out of it)

heady iris
#

look in the Hierarchy while the game is running

rotund perch
#

I would like it to be a static dictionary so other scripts can read it, but if I do that I can't see it in the inspector

#

oh wait my idea doesn't even make sense

heady iris
#

You canโ€™t serialize a dictionary in general

#

But you can certainly construct one as the game starts

#

Each prefab will contain its ID

#

Make a dictionary that maps those IDs to the prefabs

rotund perch
#

so serialize an array of prefabs somewhere, make the game read the GUIDs and assign them to a static dictionary?

heady iris
#

Yes.

rotund perch
#

is that something I can do outside of a gameobject?

willow kestrel
rotund perch
heady iris
#

Youโ€™d still need to serialize the list though

#

You can put it on an asset that gets loaded from a Resources folder

#

So it'd look a bit like this

#
public class PrefabCatalog : ScriptableObject {
  public List<Whatever> prefabs;
}

public static class GameData {
  public static Dictionary<Guid, Whatever> prefabMap;

  [RuntimeInitializeOnLoadMethod]
  static void Setup() {
    prefabMap = new();
    PrefabCatalog catalog = Resources.Load<PrefabCatalog>("Prefabs");
    foreach (var item in catalog.prefabs) {
      prefabMap[item.Guid] = item;
    }
  }
}
#

fetch the catalog from Resources, then put all of the prefabs into the dictionary

#

note that this does mean that all of the prefabs get loaded as the game starts

#

You might instead use Addressables to load the prefabs on-demand instead of immediately, but that's probably not relevant to you right now

#

(that'd be more important if each one brought in lots of heavy assets)

#

a Resources folder is a great way to "bootstrap" the game

#

it can be the one time you don't use a serialized reference

rotund perch
#

wait are the PrefabCatalog and GameData classes in the same .cs file?

heady iris
#

Doesnโ€™t really matter

#

You just canโ€™t put two unity object definitions in the same file

#

So two monobehaviours, two scriptableobjects, etc

#

Unity references the script assetโ€™s GUID, hence that rule

#

Otherwise, you can do whatever you want

rotund perch
#

I was confused how the Load function would know how to get the PrefabCatalog asset but I guess it automatically knows to just get the PrefabCatalog part

heady iris
#

It fetches an asset from a Resources folder by name

rotund perch
#

Got it

#

I think I've got enough information to start integration now

#

Looks like TMP took the Resources folder name already

heady iris
#

You can have many of them in your project.

rotund perch
#

oh I needed to read that a few times to fully understand why one needed a longer path

heady iris
#

I made a class for this

#

I've got a bunch of "catalog" assets in Assets/Resources/SingletonSO/

rotund perch
#

@heady iris so I made the public list in the ScriptableObject class but I can't see the list in the inspector

#

sorry if I'm bothering you a lot if you want I could try to search for information on the web

heady iris
#

You need to create an instance of this scriptable object

#

This is the script asset.

#

Throw a [CreateAssetMenu] attribute on it and youโ€™ll be able to create an asset

#

Make sure to throw it into a Resources folder

rotund perch
#

I'm not sure how to instance it

#

without putting it in a scene at least

heady iris
#

That attribute allows you to create instances of the asset.

#

just like creating a Material, for example

rotund perch
#

Oh that makes sense

rotund perch
#

why is OnWillCreateAsset() greyed out and yellow? It should be blue

#

probably

#

It's not being called

#

I also can't see anything under AssetModificationProcessor

#

Ping reply please when responding

#

also happy new year

somber nacelle
rotund perch
somber nacelle
#

The other thing being what you already answered yourself?

rotund perch
#

Why isnโ€™t it being called

somber nacelle
#

have you actually done anything to confirm it isn't being called? keep in mind that Console.WriteLine does not write to the unity console

quartz folio
#

It's a unity message called via reflection, so VS has no idea it's called automatically (unless that's something their Unity plugin knows about)

#

I'm not sure if VS supports the jetbrains annotations but if the Rider plugin didn't know about it would decorate it with [UsedImplicitly]

rotund perch
#

Print wasnโ€™t showing up so I had to use alternative

#

Probably shouldโ€™ve used debug.log

quartz folio
#

print is defined by MonoBehaviour

#

I would avoid it, as it's just an inferior version of Debug.Log

#

a holdover presumably added to placate people coming from certain other languages in the early days

ocean hollow
#

is there a way to make it so that variables also show references the same way functions do in vs?

latent latch
#

wrap it in a property ;p

#

if you right click it I think you can grab references to it, no?

inland sierra
#

I wanna present a game idea to someone

ocean hollow
#

present it there

ocean hollow
median wren
#

Happy New Year to @everyone ! ๐Ÿ’ซ๐Ÿค  May you stay healthy and be happy afresh... ๐ŸŽ

balmy plume
sleek bough
#

VS shows references hints only for methods and properties, you can open "Show all references" from rmb menu or with shortcut for class fields

rotund perch
#

oh wait I didn't properly understand what it was supposed to do

#

my mistake

mossy shard
#

This code is supposed to convert world positions to grid positions:


        float percentX = (worldPosition.x / gridWorldSize.x) + offsetX;

        float percentY = (worldPosition.y / gridWorldSize.y) + offsetY;  

        percentX = Mathf.Clamp01(percentX);
        percentY = Mathf.Clamp01(percentY);

        int x = Mathf.RoundToInt((gridSizeX) * percentX);
        int y = Mathf.RoundToInt((gridSizeY) * percentY);

My problem is that for the y , where the object which i convert the position of goes, the y goes in the opposite direction. Would someone know why is that? (both my offsets are 0.5f )

vestal arch
wheat spruce
# vestal arch if you have a `Grid`, there's already a function to do that <https://docs.unity3...

speaking of this, I've tried to implement my own version of this for my Grid system.

public (int x, int y) NormaliseVector2ToGrid(Vector2 pos)
{
  int x = pos.x.RoundToInt(); //(int)Mathf.Round(value);
  int y = pos.y.RoundToInt();

  x = Math.Clamp(x, 0, Width - 1);
  y = Math.Clamp(y, 0, Height - 1);

  Debug.Log($"GridPos {x} {y}");

  return (x, y);
}```It does actually return the correct value, like here the mouse position is shown as the green gizmo, and it prints `GridPos 4 7`
vestal arch
#

(int)Mathf.Round(value);
isn't there a function for this

wheat spruce
#

yeah, probably

wheat spruce
#

but point is, my implemenation seems far too simple for it to have worked correctly

#

although, could it be that becuase I have my grid originating from {0,0} which is the bottom left point, that it actually makes the process of converting from vec2 to my grids [x,y], a bit simpler?

vestal arch
#

probably

wheat spruce
#

ill see if I can enlarge the margin, so the origin is still at (0,0) but it has some additional cells in each direction

onyx cypress
dusk apex
onyx cypress
dusk apex
#

Log the value in update

#

Maybe both if and else if aren't true (the else if has an additional condition)

#

What are the sound and wander values when it misbehaves?

rotund perch
#

@heady iris I got the GUID assignment working, and now my prefabs are getting their own GUIDs, but when I instantiate the prefab or even try to edit it the GUID shows up as empty

heady iris
#

This suggests that the GUID isn't actually being saved correctly

#

How are you assigning the ID?

#

show me that code

rotund perch
heady iris
#

is that System.Guid you're using?

rotund perch
#

Yes

heady iris
#

Unity can't serialize that.

rotund perch
#

oh

heady iris
#

It looks like you wrote a custom editor to display it in the inspector?

rotund perch
#

yeah

heady iris
#

You can certainly store a value in that field, but it will only exist for the lifetime of that exact C# object

#

the data isn't making it into a prefab or scene asset

#

That's why you have to create your own Guid type.

rotund perch
#

Separator doesn't seem to do anything though

#

doesn't matter that much

rotund perch
heady iris
#

UnityEditor.GUID doesn't exist in the built game

#

it looks like it is roughly just a copy of the UnityEditor.GUID type though

heady iris
#

I did make one important change

#

I added an implicit operator so that you can convert a System.Guid into my own type

#

(it literally just turns the old one into a string and then parses that. gross)

heady iris
#

also, the odds of a GUID collision are so catastrophically low that I wouldn't even worry about it

#

One more important thing -- I'm not quite sure how the asset modification postprocessor will play with prefabs

#

It does look like it executed when you created a new prefab

rotund perch
#

yeah it did

#

it also tries to execute when I make a scene

#

but the logic weeds through that

#

it seems to work well with talking to the prefab

heady iris
#

I'll have to experiment with that

rotund perch
#

this custom guid thing definitely adds a lot of complexity than I've already added

heady iris
#

sort of; it just defines a new data type that holds four integers

rotund perch
#

what's the difference from a struct and a class?

vestal arch
#

conceptually: structs hold data, classes hold behavior

#

there are of course many exceptions and many ways to use them, and there are quite a few technical differences as well, stemming from that conceptual difference

hexed pecan
#

Except for Mathf which is a struct for some reason ๐Ÿ˜„

#

Anyway yeah and the important difference is that structs are copied when you pass them around (value type) and classes are passed by reference (reference type)

heady iris
#

a non-static struct, go figure

hexed pecan
#

var math = new Mathf()

vestal arch
#

Mathf (or the math functions object, in general) doesn't really hold data nor behavior
it's an exception to rules in every language ive seen lmao
it's more of a namespace than anything

heady iris
#

A struct defines a value type -- you directly hold the value.

#

A class defines a reference type -- you just hold a reference to the object, which exists somewhere else

#

so a List<HugeStructType> holds HugeStructType directly, whilst List<SomeClassType> just holds object references

rotund perch
#

I probably should've been using structs for these then

vestal arch
#

yeah those should probably be structs

rotund perch
#

seems like I don't get many errors for switching the class out for struct other than I'm not allowed to assign defaults I guess because it needs to be a constructor

hexed pecan
#

Structs can't have field initializers tho which is a bit annoying

rotund perch
#

yeah that

#

I don't think I need them here though

hexed pecan
#

Oh you literally just said that oops

rotund perch
#

oh there's an error

eager tundra
#

I don't think you should use structs there

chilly surge
#

I would generally not recommend to switch things to structs unless you understand what they are for and what the consequences are.

rotund perch
#

I don't really get the difference still, it's the same data just stored in different places

rotund perch
#

oh that would've been useful to appear in my google search

vestal arch
hexed pecan
rotund perch
hexed pecan
#

For example with Vector3 which is a struct, if you do cs var pos = transform.position; pos.x = 123;
This would not change your transform.position because you are modifying a copy of it

#

You'd need to assign it back

vestal arch
#

oh boy time to bust out the diagrams

rotund perch
#

structs make more sense here then

hexed pecan
#

A struct can have references to classes

rotund perch
#

yeah

hexed pecan
#

Although my structs often just have primitive types inside it

rotund perch
hexed pecan
#

If the variable is a class then yeah

vestal arch
rotund perch
#

ok so this is happening, not sure what get hash code is

vestal arch
# vestal arch

when you pass ref around, ie passing it to methods, setting in assignments, you're passing around, well, the reference
anytime you assign into that reference, the changes propagate to other references to the same object
when you pass value around, you're passing its values around like you would a primitive (which are also value types), so any changes you make don't propagate automatically

rotund perch
vestal arch
vestal arch
rotund perch
#

oh yeah that doesn't even make sense the way I did it

#

that's like a nand

#

wait no not that

#

whatever it is it doesn't make sense

vestal arch
#

A nand B = not (A and B)

#

what you have there is nor
A nor B = not (A or B)
by de morgan:
not (A or B) = (not A) and (not B)

#

so what you have there says, neither array can match up for the structures to be unequal
but logically, if only 1 doesn't match up, that still makes them unequal
so you need nand, which by de morgan is equal to (not A) or (not B)
the expanded form might make it more obvious: they're unequal if one or the other is unequal

chilly surge
rotund perch
#

they're not actually spriteshapes or objects

#

I just called them that for some reason

#

should've been spriteShapeDatas

onyx cypress
#

the startnum only increases when i make a osund over 1.1f how can i make it so it continuisl8y adds if i make a sound over 1.1f once

hexed pecan
#

In what case do you need to compare two SaveDatas?

chilly surge
#

That's not the point I was making.

#

The names don't matter.

rotund perch
#

oh

rotund perch
vestal arch
#

would you ever have re-referenced arrays though

rotund perch
#

not sure what you mean

vestal arch
#

arrays are also reference types

#

they are compared by reference

hexed pecan
#

Does each new savedata get its own arrays or are you reusing them between savedatas?

rotund perch
#

each new one gets it's own arrays

#

should I be using lists instead?

vestal arch
#

both are reference types

mossy shard
#

now it makes sense

vestal arch
rotund perch
#

I guess I need to do a comparison function then

vestal arch
#

about arrays vs lists; think about if the size will change dynamically

#

also sidenote; do you even need multiple savedatas floating around at the same time?

wheat spruce
rotund perch
mossy shard
#

i wrote mine

wheat spruce
#

ah

mossy shard
#

and mine is set to be from the upper left corener

wheat spruce
#

confirmed my suspicions that the method was calculating the wrong value. Got my grid to extend its origin point down past the actual worlds {0,0,0}, so it just clamps that position to 0

vestal arch
wheat spruce
#

its because the vector2 clamps the position like this x = Math.Clamp(x, 0, Width - 1);
so the cursor is at {-1, -1} which is below 0, so it returns 0

#
    public (int x, int y) NormaliseVector2ToGrid(Vector2 pos)
    {
      int x = pos.x.RoundToInt();
      int y = pos.y.RoundToInt();

      x += GridPadding.Left.RoundToInt();
      y += GridPadding.Down.RoundToInt();

      x = Math.Clamp(x, 0, Width - 1);
      y = Math.Clamp(y, 0, Height - 1);

      Debug.Log($"GridPos {x} {y}");

      return (x, y);
    }```this appears to fix it
vestal arch
#

im confused about what exactly the context is

#

the red sphere is the world origin, right?

wheat spruce
#

the idea is, the red circle in the middle represents the perimeter of my terrain. Theres a rectangle that surrounds the circle which is that big black square. The grid that gets created fills the region of that square. Unless I add padding, it means the grid will only ever be as large as the perimeters bounds

#

so I add some padding to make the grid a little larger than the bounds

#

but as the perimeter originates at {0,0,0}, when I convert a vector2 at the cursors position, I need to take the padding into account so it knows that {-3f, -3f} is actually [0,0]

lost dove
#

TestDummy > ModuleContainer > Orientation > EngineSlot > Thruster
These transforms have varying rotations. I ultimately need to get Thruster transforms rotation via code, so that I can align something to that rotation in the world space, independant of it's hierarchy.

    float rotation = _thrusterTransform.rotation.eulerAngles.z;

This doesn't seem to account for the absolute parent rotation.
As I rotate the parent in the unity editor, the debug log just prints out a static unchanging rotation. Although adjusting the rotation of thruster transform itself will send out a new rotation value.

vestal arch
wheat spruce
#

perhaps, I havent really been thinking of my grid in terms of world/local coordinates

#

its mostly just a data representation to store information, the tiles dont actually exist as actual world objects

vestal arch
wheat spruce
#

only when I give the left and down padding 3 units

vestal arch
#

[0, 0] on your grid is at [-leftPad, -downPad] in the world

wheat spruce
#

GridPadding = new Padding() { Top = 5f, Right = 5f, Down = 0f, Left = 0f };

vestal arch
wheat spruce
#
for(int x = 0; x < mapWidth; x++){
  for(int y = 0; y < mapHeight; y++)  {
    int index = _tilemap.GetIndex(x, y);
    int xpad = x - Grid.GridPadding.Left.RoundToInt();
    int ypad = y - Grid.GridPadding.Down.RoundToInt();
    Centroids[x, y] = new Point(xpad, ypad, _tilemap.Map[index].Zone);
    }
}```I do later generate points at the center of my tiles, as those center points will be used by my marching cubes system, becuase that needs to know where those tiles actually exist in the world
#

nice that after several iterations of designing the system, that its finally coming together

stark sun
#

How can I make joints unsplittable? I dont want those weapons to pierce between limbs but I cant make them triggers because weapons should collide with each other for things like block.

#

also I dont know why weapons dont collide?Because they are too thin?Rigidbodies are set to continious.

hexed pecan
#

You'd need to show joint settings, the code you are using and the collider and layer settings of the weapons etc.

stark sun
#

do you need ones for the characters too?

hexed pecan
#

Perhaps

stark sun
#

this is the rigidbody of the weapon

#

actually

hexed pecan
#

Why is it kinematic? Is it a child of another rigidbody?

stark sun
#

all weapons use that weapon 1 prefab

#

it gets instantiated under the slot gameobject and arm has a rigidbody

hexed pecan
#

I'm pretty unfamiliar with how parenting rigidbodies works in 2D physics, but I guess that answers the question why your weapons arent colliding

#

With each other

#

Could maybe either get rid of the weapon's rigidbody and just use its collider if you keep it as a child of the arm

hexed pecan
#

Or make the weapon's rigidbody attached with a joint to the arm

stark sun
#

I removed the rigidbody now it doesnt pierce through too.

hexed pecan
#

If you get rid of the rigidbody and still need to detect collisions (OnCollisionEnter2D) for the weapon separately, you can check which of your own colliders were hit from the Collision2D parameter

#

Not sure if you use oncollisionenter but i'd assume you want to detect hits

hexed pecan
#

The point is that you need to check whether it hits the arm or the weapon

#

Since they use the same rigidbody, the collision message will be sent to the arm

stark sun
#

I think you have helped me before so thank you again UnityChanThumbsUp

hexed pecan
#

Np ๐Ÿ‘

#

Also FYI you might want to look at physics2d settings if you run into instability issues of the joints

#

It looks stable so far tho, especially if the piercing was fixed

somber nacelle
#

this doesn't seem like a code question. and as i've pointed out to you, you can ask questions about that asset in the discord server the asset developers made #๐Ÿ’ปโ”ƒunity-talk message

topaz delta
#

I am currently starting a project in which I seperate client and server code in the editor via folders. What would be a generally accepted way to name classes according to which side they serve? E.g. the NetworkController will be needed on both sides. Would I call the NetworkController class on the server side "NetworkControllerServer" and simply "NetworkControllerClient" on the client side?

dusk apex
#

Server Controller and Client Controller? UnityChanThink

sacred python
#

hi guys
how do i check if a point is inside a triangle prims like so

leaden ice
leaden ice
topaz delta
sacred python
#

thanks

#

all try it out

topaz delta
wheat spruce
# sacred python wow didnt know that exists

The plane class also has a really convenient raycast method too, for instance it makes things very simple if all you want is to find where the mouse is clicking on the ground

#

No annoying collider/rigidbody needed!

viral oyster
#

when im using unity remote it can see my touch points but when im using an apk it doesnt

#

Potentially important Specifications:

  • visual scripting
  • set screen ratio
leaden ice
viral oyster
#

yes i think

#

one sec im starting up the project

polar marten
#

when you say "see my touch points" what are you trying to say?

#

you press on the screen, but it's as though no pointer is detected in the editor?

viral oyster
#

ok so it works fine when im using unity remote

#

but when i build it to an apk and instlal it on the phone locally it doesnt worjkm

leaden ice
viral oyster
#

yeah sorry im trying to get it to load

#

well becouse my code is a mess so im making another project to show it clearer

#

thats kinda the main part

viral oyster
#

ok well not its not even letting me use unity remote

#

nvm i fixed that

leaden ice
# viral oyster

check the logs for any errors (with android logcat, using a development build)

viral oyster
#

i have no idea what that means

#

specificaly the development build part

#

and android log chat

leaden ice
#

Development build is just a checkbox in the build settings

floral prism
#

uhm, does anyone know what conditions need to happen for this to get stuck in the loop forever?

GameObject go = new(name);
T mono = go.AddComponent<T>() ?? go.GetComponent<T>();
while (mono is null)
{
    mono = go.AddComponent<T>() ?? go.GetComponent<T>();
    Logger.Fatal("kurvo raboti we");
}

because it happens upsidedown_cry

leaden ice
#

For example you used a type T that wasn't a component type or you tried to do something like AddComponent<Transform>(), or you tried to do something like AddComponent<BoxCollider2D>() when there's already a 3D Rigidbody on the object.

#

What's the point of this loop anyway?

#

Seems like it would always be infinite if it enters at all.

floral prism
leaden ice
#

Another thing is you should not be using is and ?? with Unity component types

#

they don't work properly especially when things get destroyed.

#

Also shouldn't you be doing GetComponent first then AddComponent if it's not there?

#

e.g.

if (!go.TryGetComponent(out T comp)) {
  comp = go.AddComponent<T>();
}```
floral prism
#

and this is part of my hotloading, and im using AddComponent first because i am destroying the object when a module is reloaded

#

so it should not even exist in the first place

leaden ice
#

What's the specific case in which this is actually failing

#

What component are you trying to add

floral prism
#

its when i have the following mono attached after a hotreload:

internal class PlayerAuthorizationManager : MonoBehaviour
{
...
}
#

im not sure how this could make AddComponent to return null

#

and i just checked to make sure the GameObject is created, and it is

leaden ice
#

when you say... hot reload

#

what do you mean by that? Compiling new code while the game is running?

floral prism
#

yea basically its doing assembly,load on a new dll that contains my logic

leaden ice
#

I'm not sure that's... really possible in Unity?

#

Can the game engine handle that?

#

It probably does some kind of precaching of all the MonoBehaviour classes up front, that might not have happened with your loaded assemblies

#

and so maybe it can't AddComponent such a component properly?

viral oyster
floral prism
# leaden ice I'm not sure that's... really possible in Unity?

its kinda complex to explain, but basically i have a game server that is an unity app and when i want to inject my own code dynamically i am using a proxy assembly lets call it loader that will load and "unload" assemblies whenever i update them and will hook up and de-hook event handlers from the other modules

#

the core part of unity is staying the same

leaden ice
floral prism
#

im just doing it "event driven"

#

and im rehooking the events on each reload

leaden ice
leaden ice
#

So... does that actually work?

floral prism
#

yep it works

#

but its possesed sometimes

viral oyster
leaden ice
viral oyster
#

oh logcat?

leaden ice
#

LogCat is the package I linked you to earlier.

viral oyster
#

riiiiight

#

sorry i was confused

#

so i goota add that (done) and then do i re build the apk

floral prism
# leaden ice So... does that actually work?

i think it works because you cant really unload assemblies and they are just sitting in the background, and when i "hotload" i kill the old gameobject and create a new one with the new mono from the new version of the assembly

leaden ice
viral oyster
#

no i did

leaden ice
#

then no you don't need to rebuild

#

just connect logcat to your android device and run the game

#

And watch the logs in the logcat window

viral oyster
leaden ice
viral oyster
#

erm ok im looking a it now

#

i have no idea what any of it means but i can see when i tap it says this 2025/01/02 16:49:33.259 13832 13849 Info Unity Handle cmd APP_CMD_TOUCH_EVENT(20)

leaden ice
#

You can also see Debug.Log stuff this way.

viral oyster
#

well there doesnt seem to be any errors

#

iys just the 2025/01/02 16:49:33.259 13832 13849 Info Unity Handle cmd APP_CMD_TOUCH_EVENT(20)

leaden ice
#

So what's actually not working

viral oyster
#

its just not lettinf me drag them around

#

i dont knwo why

leaden ice
#

drag what around

viral oyster
#

The square

#

Front the original video I sent

#

But also I made my own debunking interface thing and it's just not registering my touch

willow oak
#

Hi Guys I started using unity 2022 LTS like 6 months ago in some projects .
But now I'm thinking about making another project an fps game with survival and fighting elements.
I just want to know should I use Unity 6 or it's a bad idea.
keep in mind that I already used it and It's good. but I want someone who used it more than me to give me advice ,Thanks

knotty sun
willow oak
#

For now the only thing that I don't like is importing assets in unity 6 changes them a little bit and I sometimes lose some colors ,any idea how I should fix it ?

knotty sun
hardy pasture
#

What's the default and preferred way to change position?
I want to write something like this: GameObject.transform.position.y += 1.
Which doesn't work, of course.
The first thing that comes to mind is something like this:

  var Position = GameObject.transform.position;
  Position.y += 1;
  GameObject.transform.position = Position;

A little bit verbose for changing a float.
I can probably write extension methods like:

void Change(this Vector3 Position, float X, float Y, float Z = 0) {
  var NewPosition = GameObject.transform.position;
  Position.x += X;
  Position.y += Y;
  Position.z += Z;
  GameObject.transform.position = NewPosition;
}

void ChangeX(this Vector3 Position, float X) {
  var NewPosition = GameObject.transform.position;
  Position.x += X;
  GameObject.transform.position = NewPosition;
}

void ChangeY(this Vector3 Position, float Y) {
  var NewPosition = GameObject.transform.position;
  Position.y += Y;
  GameObject.transform.position = NewPosition;
}

void ChangeZ(this Vector3 Position, float Z) {
  var NewPosition = GameObject.transform.position;
  Position.z += Z;
  GameObject.transform.position = NewPosition;
}

Any better solutions, guys?

leaden ice
#

I use the extension way as well

shrewd fog
#

Hello,

From a monobehavior, as a field, is it possible to reference a graphView Node input port ( List<GameObject> ) , thanks ?

knotty sun
leaden ice
#

Yeah none of those extensions should be referencing any GameObjects

hardy pasture
#

Oh yeah it's a mistake

#

I just wrote it here in Discord

hardy pasture
knotty sun
hardy pasture
#

Yep, me too

#

I need to take it by reference or something

#

So I change it in place

leaden ice
#

You don't need a reference to the GameObject at all in such an extension

#

I use one in a form like:

transform.position = transform.position.WithY(5):``` for example
#

Just an extension on Vector3

hardy pasture
knotty sun
hardy pasture
#

Or this might be enough

leaden ice
#

Yeah you can avoid the second copy

chilly surge
#

Imagine if we had record struct, we could've had position = position with { y = 5 }; for free.

knotty sun
willow oak
#

Do you guys recommend any fps character tutorial ?
I'm planning to use NetcodeForGameObjects andI only used mirror before

hardy pasture
#

Thanks guys

#

Added this now, too:

public static class TransformExtensionMethods {
    public static void TranslateX(this Transform Transform, float X) {
        Transform.position += new Vector3(X, 0, 0);
    }

    public static void TranslateY(this Transform Transform, float Y) {
        Transform.position += new Vector3(0, Y, 0);
    }

    public static void TranslateZ(this Transform Transform, float Z) {
        Transform.position += new Vector3(0, 0, Z);
    }
}
still jungle
#

why would you spam create Vector3

vestal arch
knotty sun
cold parrot
#

you just end up coupling your code to some โ€˜convenience libraryโ€™ nobody needs.

#

it does not improve readability

vestal arch
#
- transform.TranslateX(x);
+ transform.Translate(x, 0, 0);
(or)
+ transform.Translate(Vector3.right * x);
still jungle
#

create Vector3.zero, cache it, keep manipulating it, if you want to apply changes on that vector3 to position just write it back to transform.position

thin aurora
#

Caching a value type doesn't really improve anything

hardy pasture
vestal arch
#

this makes it harder to do non-orthogonal translates

- transform.TranslateX(x);
- transform.TranslateZ(z);
+ transform.Translate(x, 0, z);
- transform.TranslateX(direction.x);
- transform.TranslateZ(direction.z);
+ transform.Translate(direction);
hardy pasture
#

I'll use Translate when it makes sense: when it's less verbose

vestal arch
#

not making the programmer type more than they have to
i think you're misinterpreting this as literally typing less.
if we followed that we'd have single-letter variables and methods

hardy pasture
vestal arch
#

"more than they have to" means you don't have to go out of your way to say something indirectly

vestal arch
#

you've made code more specific, so any change in the behavior would involve changing what methods to use, instead of just changing values

quartz folio
#

Who cares if it's local to a project imo

vestal arch
#

i mean, i kinda care when it might be posted here in the future without context

hardy pasture
thin aurora
#

Also don't forget the TranslateXY, TranslateXZ, TranslateYZ and TranslateXYZ methods if you're going to be utterly specific

vestal arch
quartz folio
#

If you needed those then you just use Translate

thin aurora
#

Also don't forget overloads with Space relativeTo as a parameter

#

Also Transform relativeTo

#

On second though, maybe it's not such a good idea after all

vestal arch
still jungle
# quartz folio This is so unnecessary

Why is that? It is the same type of movement he wanted to use, just without spam the heap. There is always Translate method to use if he need relative movment

still jungle
#

nice, didnt know its struct

thin aurora
#

If it were a class, it would be different

hardy pasture
# thin aurora Also don't forget overloads with `Space relativeTo` as a parameter

I very much might add overloads for the relative to and use them, yeah.
https://youtu.be/SVRiktFlWxI?t=5960

Rabobank Livestream 2019 with Uncle Bob | A session about clean coding

The program:
09.00 Uncle Bob - Part 1
11.00 - Break
11.20 - Uncle Bob - Part 2
12.30 - Lunch
13.30 - Breakout sessions (NO LIVE STREAM)
15.30 - Uncle Bob - Part 3 - Including Livestream.

#werkenbijRabobank #RabobankIT #unclebob

โ–ถ Play video
#

Here's the Unity's Translate method:

    public void Translate(Vector3 translation, Transform relativeTo)
    {
      if ((bool) (Object) relativeTo)
        this.position += relativeTo.TransformDirection(translation);
      else
        this.position += translation;
    }

It is worse than:

    public void Translate(Vector3 translation)
    {
        this.position += translation;
    }
    public void Translate(Vector3 translation, Transform relativeTo)
    {
        this.position += relativeTo.TransformDirection(translation);
    }

Because it's really just 2 different methods with 2 different implementations.

#

The relativeTo is a boolean in this case, too.

thin aurora
hardy pasture
#

Yes

#

Having to pass unnecessary arguments into functions is annoying and unnecessary

#

Also error-prone

#

And harder to understand

cold parrot
#

you need to stop drinking uncle bob cool aid

#

this stuff (ideas of clean, dry, solid etc) is extremely outdated/incomplete and in many cases tangential or irrelevant to gamedev.

vestal arch
quick token
#

(bool) (Object) completely unrelated but i have never once seen 2 typecasts for a single variable

cold parrot
#

these principles do not express absolutes that can be maximised, they all have a cost and removing some parameter from a .Translate() call is such an unimportant thing to care about in the grander problem space of finishing and maintaining a project its almost ridiculous.

#

if anything, the overriding argument for NOT extending an API is to maintain standardisation.