#archived-code-general

1 messages ยท Page 94 of 1

heady iris
#

that is not a scriptable object

#

it is a plain old C# class

#

is that intentional?

pure dragon
heady iris
#

it should still work fine

pure dragon
#

apparently not

rigid island
heady iris
#

show me a screenshot of the HealthManager component in the inspector.

pure dragon
heady iris
#

also, what version of unity is this?

somber nacelle
#

have you also made sure to save your HealthManager script after adding the list field?

pure dragon
#

2021.3.11f1

pure dragon
heady iris
#

and make sure that compilation happens -- you should get a popup for a few seconds

#

and then console should be empty.

somber nacelle
pure dragon
#

yep, also regenned meta files a few times

#

and also deleted and remade the scripts

#

reimported all

#

and reloaded unity

simple egret
#

Do you have a custom inspector set up for that script? I would expect the file name to appear in a read-only field at the very top of the component

heady iris
#

oh yeah

#

good point

#

that's a custom editor

pure dragon
heady iris
#

that's not what SPR asked

#

they are asking if you've defined a custom editor for this class

pure dragon
#

no, no custom inspectors i mean

heady iris
#

it sure looks like you do, because there should be a grayed-out field called Script at the top

pure dragon
#

damn your right might be onto something there

somber nacelle
#

name the class (and obviously the script file) something different (without using the actual refactoring tools) and remove then re-add the component and see what happens.

pure dragon
#

no i dont but that could be a clue

heady iris
#

ctrl-shift-f your project for CustomEditor

rigid island
pure dragon
#

yes ok so a new script called Test2.cs works fine at displaying the health

somber nacelle
#

it for sure sounds like you have a custom inspector for that type that you need to find and fix (or just stop using altogether)

pure dragon
#

yeah i think thats it mightve been a custom inspector i deleted and forgot about

simple egret
#

Search all the files in your project for custom inpectors

rigid island
#

has to be, also you're missing this on your script

heady iris
#

the dots! the dots!

rigid island
#

wait nvm I thnk the screenshot is just cutoff

heady iris
#

so this is what they meant by DOTS

#

more weird dot menus

rigid island
#

in debug mode though you should be able to see if it's correctly link

pure dragon
heady iris
#

right

#

that does a project-wide search

pure dragon
#

ah yep thats it

#

some random defunct tiny script i forgot about

#

thanks

rigid island
#

when someone asked if you had custom inspector doesn't that click to be a reminder of what you did ?

pure dragon
#

plus i wrote it ages ago thought its not worth the effort and left it alone

quartz folio
rigid island
#

I mean they did say ALL Custom

#

but glad it's solved

pure dragon
#

yeah thanks for that

rigid island
#

nice too see Debug mode is mentioned ๐Ÿ™‚
thought I yelled at deaf ears

soft shard
somber nacelle
pure dragon
rigid island
#

mans a JS pro Xd

#

those charts are kinda hot ngl

quartz folio
soft shard
#

Speaking of physics, I came across your shape debugger for raycasts and such a while back, incredibly helpful git

rich leaf
#

Hey. Is there a way in unity to instantiate a unique scriptable object at runtime?

I have a chest prefab that stores items. If I have a second chest that can be spawned by the player, i need it to have a seperate inventory than the first chest. How can I do this?

On the script attached to the chest, I've tried:

    _chestInventory = Instantiate(chestInventoryBlueprint); 
    chestMenuPrefab.inventory = _chestInventory;

(where chestInventoryBlueprint is an InventoryObject that is set up how I want all my chests to be set up ie number of slots, allowed items in each slot, etc...) in the start() method. The inventoryobject. is a scriptable object However, it seems like if there is a second chest prefab in the scene, they still share the same inventory with each other.

heady iris
#

so removing an item from one causes the other to also lose an item?

#

does this also modify the original asset?

rich leaf
#

No, the blueprint is not modified. And yes, removing an item from one causes the other to lose it

#

Like its succesfully creating a clone of the blueprint, but the problem is that all the prefabs share the same clone

heady iris
#

i wonder if they're winding up with the same list reference

#

but since it's serializable, then i wouldn't really expect that...

leaden ice
somber nacelle
#

if you call Instantiate on a ScriptableObject is clones it, including the currently set properties, no? Wouldn't it make more sense to use CreateInstance to create a brand new instance of the ScriptableObject with none of the properties set to the existing values?

leaden ice
#

Your question pivots on what kind of data exactly is stored inside the SO and whether it's serialized, etc...

rich leaf
heady iris
#

show us your code

#

we're spitballing here

heady iris
#

at the very least: one paste for the SO, one paste for the chest

rich leaf
#

_chestInventory = Instantiate(chestInventoryBlueprint);
chestMenuPrefab.inventory = _chestInventory;

deep fable
#

If I have a quaternion that is made using Quaternion.LookRotation(direction) and I want to rotate the quaternion along the direction axis by X degrees, how do I do it?

heady iris
#

we are looking at random lines of code here

#

it's like trying to debug through a mail slot

deep fable
rich leaf
#

The script for which? The chest object or how the inventory system works?

heady iris
#

Both.

#

Show us the code. We are just guessing what's going on here.

rich leaf
#

In the chest script that is the only code

heady iris
#

no, that is not the only code, because that would not be a valid C# class..

rich leaf
#

that references the inventories

heady iris
#

please, just do it

#

!code for how to share it

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.

rich leaf
#

One min, i want to try using the other method really quick. For the creating instance suggestion,
'''
_chestInventory = InventoryObject.CreateInstance<InventoryObject>();
'''

#

is there a way to make _chestInventory inherit all of the properties of the blueprint now?

heady iris
#

you have not shared your code

#

i am not going to provide advice until you share your code

somber nacelle
#

but seriously, you need to share more context or you won't get accurate help

rich leaf
#

The issue is that at runtime, any changes to one would affect the other. I wanted them to be instantiated with the same properties to start, but when the player is interacting with them it only affects the one

somber nacelle
#

well you still haven't shown enough context so until you do you're not going to get any help ๐Ÿคทโ€โ™‚๏ธ

rich leaf
#

Im not really asking for help to debug my code in specific, i am trying to understand how it works in unity with scriptable objects

brisk axle
#

hey there, assuming I'd like to make a rogue-like game with classes. would the best way to achieve this using a GameManager class that holds all the powerups (offered at the end of every level), the selected class, etc.? kind of a game state, I guess

tropic quartz
#

I'd really like to see the bit where you declare your variables, for one. Like what access modifiers that _chestinventory has.

heady iris
#

seems reasonable

brisk axle
#

so it wouldn't be an anti pattern to use it for that purpose?

#

most tutorials I've found regarding gamemanagers simply keep track of the game is paused and things like that. selected classes, powerups, etc. seems a bit more "higher" level

heady iris
#

you can't get much higher level than a singleton game manager :p

#

I guess that it might be smarter to just have the player object hold the powerups

brisk axle
#

that would also make sense

near cave
#

When creating a 2D game, should i use multiple tilemaps to differentiate between layers?

somber nacelle
#

yes, not a code question btw

near cave
#

For example, a tilemap for the ground layer, a tilemap for walls, a tilemap for objects ect

#

oh my bad, didn't see its code only

rigid island
weary marlin
#

can someone help me out with parent/child transforms? im having trouble with getting myhead around it

#

ill try to explain what im trying to do

#

i made this first using a single monobehaviour but decided to separate each wall segment into a separate prefab

#

and laying out tiles within the single wall segment works fine however im having trouble layout out the segments into a square afterwards

#

i thought applying a transform to the prefab itself would apply it to all children recusively however that isnt happening

#
using Assets.Prefabs.Wall;
using UnityEngine;
using Zenject;

public class WallBehaviour : MonoBehaviour
{
    public GameObject Pivot;
    public GameObject WallSegmentPrefab;

    [Inject] private DiContainer diContainer;
    [Inject] private IWallConfiguration wallConfiguration;
    
    void Start()
    {
        for (int seg = 0; seg < wallConfiguration.SegCount; seg++)
        {
            var distanceFromCenter = -(Constants.TileHeight + Constants.TileWidth * (wallConfiguration.ColCount / 2.0f + 0.25f));
            var wallSegment = this.diContainer.InstantiatePrefab(this.WallSegmentPrefab, Vector3.zero, Quaternion.identity, this.gameObject.transform);

            wallSegment.transform.Translate(0, 0, distanceFromCenter);
            wallSegment.transform.RotateAround(this.Pivot.transform.position, Vector3.up, seg * -90.0f);
        }
    }
}
#
using Assets.Prefabs.Wall;
using UnityEngine;
using Zenject;

public class WallSegmentBehaviour : MonoBehaviour
{
    public GameObject TilePrefab;

    [Inject] private DiContainer diContainer;
    [Inject] private IWallConfiguration wallConfiguration;

    void Start()
    {
        for (int col = 0; col < wallConfiguration.ColCount; col++)
        for (int row = 0; row < wallConfiguration.RowCount; row++)
        {
            var tile = this.diContainer.InstantiatePrefab(this.TilePrefab, Vector3.zero, Quaternion.identity, this.gameObject.transform);

            tile.transform.Translate(Constants.TileWidth * col, Constants.TileDepth * row, 0);
            tile.transform.Translate(-(Constants.TileWidth * (wallConfiguration.ColCount - 1.0f) / 2.0f), Constants.TileDepth / 2.0f, 0);
        }
    }
}
#

specifically, these lines in WallBehaviour seem to have no effect:

#
            wallSegment.transform.Translate(0, 0, distanceFromCenter);
            wallSegment.transform.RotateAround(this.Pivot.transform.position, Vector3.up, seg * -90.0f);
#

which are supposed to move each segment away from center (defined by an empty Pivot GameObject placed in the center and rotate by multiples of 90 degrees

soft shard
# brisk axle hey there, assuming I'd like to make a rogue-like game with classes. would the b...

If your game manager is mostly just holding references and firing or subscribing to events, I think that sounds like a fine approach, though if your powerups are something that gets spawned in the scene, maybe it should be controlled by a "director" or "service" instead, if its just specific objects thats requesting powerups, it might make more sense to put those powerups in a ScriptableObject and reference it on the object(s) that need them - the game manager could keep track of a "game state" though (which could act similar to a state machine with classes as states or a simple enum if states act morel like checks over needing to execute any logic), for example, you could make the current state a property, and fire a event when the state changes, maybe some of those methods could work for your game

weary marlin
#

regarding my problem - it looks like the wall behaviour is executed completely before wall segment behaviours are instntiated

#

i assumed the code would be run synchronously

#

and that the InstantiatePrefab(wallSegmentPrefab) would execute WallSegmentPrefab's Start() method

bright relic
#

im trying to figure out how to write a script for procedural mesh generation, my goal is to create a gridbased mesh just like the picture i added from a heightmap i could make in asperite. i think i can write a script so all the horizontal faces will be at the right position. i just cant find any resources on how to connect those faces with vertical faces https://gyazo.com/eb58b8bbcb8dfdaf2d135c17725dfe89

#

it would probably be easiest to just make cubes extended to the height they need to be at, but for performance and texturing i'd like it if it were a plane with extruded faces

thorny onyx
#

what would be the best way to make a physics based update on the press of a button

#

cause in fixedUpdate the button isnt always registered

#

and in update the physics is varied by the framerate

#

i could make a variable thats activated but i feel like my code gets cluttered that way

#

already too cluttered

heady iris
#

check for input in update

#

respond in fixedupdate

rugged storm
#

yo I have a dictionary of tiles with their key being it's position, defined as cs public Dictionary<Vector2, Tile> tiles;

slate urchin
#

I'm having an issue with this code:

        if((MonstersSearching[i].Stamina <= 2 || OfflineResting[i])&& offlineSearchingDone[i]>0){
        float decreasePerSecond = 50 / (Mathf.Log(MonstersSearching[i].AgiV / 100f, 4f) + 1f);
        if(MonstersSearching[i].Resting){
        MonstersSearching[i].Stamina += MonstersSearching[i].ConV * 0.01f;
        offlineSearchingDone[i] -=decreasePerSecond;
        OfflineResting[i] = true;
        if(MonstersSearching[i].Stamina>=MonstersSearching[i].ConV){
            OfflineResting[i] = false;
        }
        }
        } else{
            
            lootTable.SearchingCommon(MonstersSearching[i].Location);
            int ForUncommon = Random.Range(1,61);
            int ForRare = Random.Range(1,10001);
            int ForRelic = Random.Range(1,1000001);

            if(ForRelic == 1){
                lootTable.SearchingRelic(MonstersSearching[i].Location);
            }

            if(ForRare == 1){
                lootTable.SearchingRare(MonstersSearching[i].Location);
            }

            if(ForUncommon == 1){
                lootTable.SearchingUncommon(MonstersSearching[i].Location);
            }

            MonstersSearching[i].Stamina -= 1;
            offlineSearchingDone[i] -= 50;
        } }```
the game will not load. if i remove MonstersSearching[i].Stamina -= 1; it loads fine. or it will run fine if i remove:
```if(MonstersSearching[i].Resting){
        MonstersSearching[i].Stamina += MonstersSearching[i].ConV * 0.01f;
        offlineSearchingDone[i] -=decreasePerSecond;
        OfflineResting[i] = true;
        if(MonstersSearching[i].Stamina>=MonstersSearching[i].ConV){
            OfflineResting[i] = false;
        }
        }
        } else{```
I dont understand why Stamina is causing issues.
rugged storm
#

whats a good way to find a 2x3 group of tiles where tile.isEmpty = true for all of them? (basically find a area of tiles that are empty?)

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.

lucid valley
#

also probably you'll need to learn how to use the debugger

#

breakpoints will help you here

#

but i'm just gonna guess you have an infinite loop due to that while loop never finishing

slate urchin
lucid valley
#

please use a proper ide

#

visual studio is recommended

#

!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.

lucid valley
#

and remember to configure it

slate urchin
ashen yoke
#

invalid what

shut wadi
#

Hello all ! How can I change the alt negative button of my Input Manager via script ?

shut wadi
rugged storm
#

yo I have a dictionary of tiles with their key being it's position, defined as

public Dictionary<Vector2, Tile> tiles;```
what's a good way to find a 2x3 group of tiles where tile.isEmpty = true for all of them? (basically find a area of tiles that are empty?) i want to use it return a list of tiles where ill spawn the player.
timber cloak
leaden ice
#

Dictionary is a good idea if the data is sparse

leaden ice
#

To check the 6 spots

timber cloak
rugged storm
# leaden ice You should use Vector2Int not Vector2

ah i thought just pick a spot, look at its neighbors in the relevant area and check them and if it fails pick a new one? but I'm not sure how to repeat it until it actually finds a valid option, or how to detect if there is no valid option and just make a new set of tiles

leaden ice
#

If you check every coordinate and find nothing, time to make a new set

ashen yoke
heady iris
#

for a given corner, you see if any tiles exist in the corresponding 6 spaces

ashen yoke
#

instead of v2 you should floor it into v2i so that the hash of (0.1,0.5) == (0.004, 0.999)

#

because both positions are in the same cell

rugged storm
leaden ice
#

There shouldn't be any need to floor things

ashen yoke
#

depends heavily

#

if all the values are in positive space yes you can just cast

#

if it goes into negative youll get problems

leaden ice
#

It should all be in integer coordinates in the first place. The exception being maybe a query to check the coordinate of a mouse position or something

slate urchin
rugged storm
#

I want to randomize it not just find the first valid result so could it be a good idea to make a copy of _tiles, randomize it's order and then do a foreach loop on? exiting the loop once I find a valid position, and if i make it to the end without finding one making a new tileset?

ashen yoke
#

anyway if you have a sparse set you can keep bounds or min/max and update it on inserts

#

so that you have at least known area or you can use each existing node in the set and keep visited set

#

so that you do the search around existing nodes

rugged storm
#

okay cool

leaden ice
#

You have to be careful not to make an infinite loop here

rugged storm
#

well im doing foreach, so it will eventually hit the end of the tiles,

#

at which point if we haven't already returned a list of tiles in the area I need, it will return null probobly and then what I'm calling this FindAreaOfTIles() will handle that accordingly

leaden ice
#

Right but you mentioned trying again if you don't find a legal space

#

What if that keeps happening?

rugged storm
leaden ice
#

Right:

restart the grid making process
Is what I'm worried about.

What if you restart the grid making process and there's again no legal spaces?

rugged storm
#

it would basically just do the whole process again,

#

it wont move forward in the logic unless I tell it to progress the gamestate

#

so it will keep looping untill eventually it works

#

and i mean technically theoretically it could repeated make invalid boards... ill add like a fail safe that throws an error if it runs like 100 times without working

heady iris
#

i would just give up, destroy some tiles, and spawn the player :p

#

in fact, if the tiles aren't super well-structured (maybe they're just random junk in a field), you could use that as a spawning algorithm

#

carve out tiles to make room for whatever needs to be spawned

slate urchin
rugged storm
#

yo ive made it to this so far but how do i pull back out to the foreach loop?

lean sail
#

!code

tawny elkBOT
#
Posting code

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

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

lean sail
#

Also, what do you mean "go back to the foreach loop", you are still in the loop. Do you mean continue?

#

continue wouldnt actually exit the inside for loops

rugged storm
#

yeah, would that go to the foreach loop or continue the for loop?

#

oh

lean sail
#

you would need to add a bool then to exit those early. Or put your for loops inside a function and return early

oblique spoke
#

Could also set the iterators to the max value and continue

dusk apex
rugged storm
rugged storm
#

IK its not the best way

dusk apex
#

Yeah, setting h to areaHeight and calling break would escape the two loops.

rugged storm
#

but its simple and doesn't seem thaaaat bad...

oblique spoke
#

Yea setting the iterators could have some side effects in loops where the outer loop does logic after the inner loop

lean sail
#

wow magic, my O(n^3) became O(n) by putting it in a function

heady iris
#

computer scientists hate him!

rugged storm
#

so just throw the whole foreach loop into it's own method? or make a method replacing the inside of the foreach loop? with a method

dusk apex
#
void n2InnerLoop(Tile tile)
{
    for(...)
    {
        for(...)
        {
              if(...)
                  return;
        }
    }
}
foreach(...)
{
    n2InnerLoop(tile);
}```
lean sail
#

Only the loops u wish to exit from

rugged storm
#

alr

grim copper
#
    {
        
        recoil.DoRecoil();
        audio.Play();
        CameraRecoil.RecoilFire();
        animator.SetTrigger("Shoot");

        
        readyToShoot = false;

        //find the hit position
        Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)); //ray that goes through the middle of the view
        RaycastHit hit;

        //check if ray hits something
        Vector3 targetPoint;
        if (Physics.Raycast(ray, out hit))
            targetPoint = hit.point;
        else
            targetPoint = ray.GetPoint(75); //Just a point far away from the player

        //calculate direction from the targetpoint to the attackpoint
        Vector3 directionWithoutSpread = targetPoint - attackPoint.position;

        //calculate spread
        float x = Random.Range(-spread, spread);
        float y = Random.Range(-spread, spread);

        //get a new direction and add spread
        Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0); //Just add spread to last direction

        //Instantiate bullet/projectile
        GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);


        //Rotate bullet towards shoot direction
        currentBullet.transform.forward = directionWithSpread.normalized;

        //Add forces to bullet
        currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
        currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse);

this is an annoying bugI've got a code that shoots/instantiates projectiles at a certain velocity from the barrel of a gun. they work fine but when i shoot too close to walls the bullets pretty much just don't work and dissapear and whenever i look down enough they shoot in exactly the opposite direction into the players face.
i tried fixing it but it wont work

dusk apex
#

Well, it can't just disappear.. where does it go?

grim copper
#

so the bullet has a script attached to it

#

basically on collision it destroys itself

#

cuz it fires prefabs

dusk apex
#

So it immediately destroys itself. Sounds like a functioning behavior.

grim copper
#

yeah but it never collides with the wall

dusk apex
grim copper
#

like you can shoot while standing in the door frame and if you go too close to the sides it 'collides'

dusk apex
#

Staying close to the wall implies it's going to hit the wall asap.

grim copper
#

i can maybe send a video would that help

#

the more annoying bug is when i tilt down it shoots the opposite way

dusk apex
#

Log when it hits something and the thing it hits. Check if it's hitting the wall.

grim copper
#

okay

lean sail
#

also play it frame by frame assuming the bullet takes more than a frame to hit something

#

so u can see where it is

lean sail
#

either pause the game manually or insert a debug.break when u shoot so it pauses the game for u

grim copper
#

im gonna record a quick video

lean sail
#

try and debug what happens yourself given what we said first ๐Ÿ‘

grim copper
#

yeah

dusk apex
#

As for the floor, log the direction or debug a ray that'd illustrate the direction shot: cs Debug.DrawRay(attackPoint.position, directionWithSpread.normalized * shootForce, Color.red, 5f);

grim copper
#

Okay thanks, I did what you said and wrote this line of code:
Debug.Log("the bullet has collided with" + collision.gameObject.name);
on collisionenter

lean sail
#

(dont forget to turn on gizmos to see the debug ray)

dusk apex
#

Hmm, why did you apply a second set of force relative to camera up?

grim copper
#

it claims to be colliding with the walls but its impossible

grim copper
dusk apex
#

That doesn't answer the question though UnityChanThink

grim copper
#

wait lemme see

#

this?

currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse);

dusk apex
grim copper
#

Should I send a quick video it can probably explain better than I could

#

whoops

#

im standing a doorframe

#

which i can walk through just fine

#

when i hug the sides

lean sail
#

that just looks like ur colliders arent proper

dusk apex
#

Is there a collider there?

grim copper
#

yeah its just a probuilder collider

dusk apex
#

Colliders could possibly stop the bullet.

#

You still haven't shown the log or the drawn ray.

grim copper
#

sorry, the log says 'collided with arch (my walls)'

lean sail
#

Also the bullet may not be spawning where we think it is, so draw some lines to show where the bullet spawns and its path. did u play frame by frame?

red scarab
#

I sent a build to my friend for beta testing. Nothing fancy just a 2D game, the entire .zip is 22MB and has a .exe ... his Norton antivirus is blocking it, claiming "telepathy.dll is unsafe" and "Unity.Timeline.dll is unsafe" and so on and so on... what am I supposed to do so the builds don't get flagged by antivirus?

dusk apex
dusk apex
lean sail
grim copper
lean sail
#

Also Norton is really really bad..

grim copper
#

ignore that line 21 error its just complaining i disabled my enemy

#

it happens with enemy enabled too

red scarab
lean sail
#

unless u put the game on steam, probably not

#

its possible for malware to exist in a game, antiviruses will check for it

lean sail
# grim copper

highlight the actual collider for yourself too, its impossible for us to see where these rays are in 3D space because of depth perception

grim copper
#

the player collider?

sorry if im being stupid

lean sail
#

the wall it is colliding with

grim copper
#

it's highlited, those little white lines i believe

#

ik its usually green

lean sail
#

i see a single white line across the bottom, which would indicate to me that your bullet shouldnt pass through that at all

grim copper
#

yeah, but i can pass through the door just fine

lean sail
#

theres a few cases here,

  1. your wall collider doesnt exactly line up with the mesh
  2. the bullet doesnt spawn where its supposed to and is taking a path that looks like it goes through the entrance but doesnt.
  3. both cases above
  4. you have an extra collider somewhere
dusk apex
lean sail
#

and more that arent directly related to the collider

grim copper
lean sail
#

dont rely on me to look at your scene please. Im not gonna inspect your collider size and compare it to the bullet path

#

pause the game as soon as the bullet hits the wall maybe and debug everything to see whats really happening

sour zealot
#

Help...

dusk apex
lean sail
#

your rays as well might be not accurate since i dont know what u wrote. Your rays might be showing the intended path but the bullet mightve not taken that entire path

sour zealot
#

im getting this error, its in the third person starter assets pack: 'PlayerArmature' AnimationEvent 'OnLand' on animation 'JumpLand' has no receiver! Are you missing a component?

vagrant blade
#

Your animation JumpLand has an animation event calling OnLand but there's nothing for it to target.

grim copper
#

Okay well I've just figured something out

rugged storm
#

any glaring issues?

lean sail
#

u tell us, does it work?

grim copper
#

because i made a doorframe out of box colliders with blocks and it worked fine

rugged storm
grim copper
#

Okay well i've fixed my doorframe collider issue by just messing with the bullet's rigidbody somehow but there is still the issue of whenver i look down the bullet fires in the exact opposite direction and even the rays just show it like completely firing from the attackpoint the opposite way it's supposed to

lean sail
#

a rigidbody alone shouldnt have done much... but im glad it worked

#

that might be if it collides with the player hand/gun/floor/anything when it spawns, it might instantly bounce back. Unless u have it destroy on any collision at all

dusk apex
#

Log your target point, attack point position and camera point.

#

The resulting direction would be the result of those two.

grim copper
dusk apex
#

If origin is below target (you're shooting from the camera and not the attack point with the ray check) the shot would be in the opposite direction.

grim copper
#

yeah its meant to just shoot to the middle of the screen

#

thats what the ray is for

#

but i'll do that rq

#

Okay I aimed all the way down

target point pos (4.60, 2.37, 10.65)
attack point pos (4.76, 1.71, 10.99)

dusk apex
#

So the target is above the attack point.

#

Meaning you'll be shooting up.

#

target - attack = direction

grim copper
#

right

dusk apex
#

This is occurring because the initial raycast is from camera and not the attack point.
After determining the point of collision relative to the camera, use a ray generated from the attack point as the actual shot ray.

#

Wait.. I believe that's what you did.

#

Issue is the attack point is below the expected collision.

#

ie your gun is through the floor etc

grim copper
dusk apex
#

Depends if you're wanting to shoot through the floor or whatnot, you'll need to implement a feature for dealing with shots where your gun (attack point) is through the floor or below the collision point.

grim copper
#

yeah

dusk apex
#

Basically camera sees the collision point above the attack point so shots are being fired towards yourself.

#

You may be hitting other things such as your lower body with the initial contact point though - only you'll be able to determine this with debugging.

grim copper
#

the rays show that it just goes the opposite way

dusk apex
#

Bullet shouldn't be able to hit itself. Check what you've hit when shooting down.

#

The log would tell.

grim copper
#

It doesn't hit anything as it just shoots into the sky

dusk apex
#
if (Physics.Raycast(ray, out hit))
{
    Debug.Log($"Camera ray hit: '{hit.collider}' at point {hit.point}");
    targetPoint = hit.point;
}
else
    targetPoint = ray.GetPoint(75); //Just a point far away from the player```
solemn raven
#

what the hell is that ?

Should not be capturing when there is a hotcontrol
UnityEditor.EditorGUILayout:PropertyField (UnityEditor.SerializedProperty,UnityEngine.GUILayoutOption[])
#

should i ignore it ?

dusk apex
solemn raven
solemn raven
rugged storm
#

lmao i wonder if one day someone will play it and get a map thats litterally entirely unwalkable besides where the players spawn, and a path to the enemies(which i will also be checking for making sure exists)

heady iris
#

i suppose there are two ways to produce a level

#

one is to generate features, and then subtract the ones that get in the way

#

the other is to figure out what areas can be filled in, and then generate features in them

fluid lily
#

So I am having an issue of compile times. I am using assemblies, but it is taking 1-2min everytime I save a change to a scripts, and that combined with 1-2min to get into play mode is a killer on productivity. The playmode I have fixed by using a test scene, but the compile time is still there.

#

My assemblies have like 50+ scripts each, so maybe time to split them down some more? Can you have sub assemblies?

#

Also is there a setting to stop unity from compiling while I am in VS?

heady iris
#

you can tell unity to only reload when commanded

#

i do that

fluid lily
#

Cool, because if I am creating a new script it makes sense to reload after each change, but I am currently just cleaning code up, and it is eating so much of my time lol

heady iris
#

i wish i could tell it to hold off while I'm moving scripts around

fluid lily
#

indeed

viscid kite
#

what's the best way to implement a hit stop on say a per hit basis? Should it simply be a global timescale set to 0 for a short period of time or something else?

heady iris
#

that's what I've done in the past

#

a very short period of 0 timescale

#

some effects may need to then be set to use unscaled time

#

e.g. a camera shake during the stop

viscid kite
#

eye sea

heady iris
#

also, if you do this in a coroutine, make sure to use WaitForSecondsRealtime ๐Ÿ˜›

fluid lily
#

Or eye sea what you did there

silk tinsel
#

is there a way to change the position of a sprite renderer component relative to the gameobject it is attached to?

somber nacelle
#

change its localPosition instead of position

#

or rather, make it a child of the gameobject and do so

silk tinsel
#

that still changes the position of the gameobject in world, not the component itself

#

i need the sprite renderer to be attached to a gameobject but be visually at a different location than the gameobject itself. I can't attach it to another child gameobject

somber nacelle
#

is this actually not a code question but rather a "my sprite isn't in the right position when i add it to the gameobject" question? because that would just be changing the pivot point of the sprite

silk tinsel
#

no I need to update it at runtime to be at a slightly different position than the actual gameobject it is attached to for pixel snapping purposes

leaden ice
silk tinsel
#

but if I change the position of the actual gameobject it leads to desyncing between the gameobject with the sprite renderer component attached whenever sub-pixel motion occurs

silk tinsel
silk tinsel
#

it isn't letting me set it, according to rider it only has a getter

#

I'm just trying to set it to a random offset here for testing purposes

leaden ice
#

Well that's annoyingly undocumented

somber nacelle
silk tinsel
#

yeah it is lol

leaden ice
#

Options then are:

  • create a new sprite with a different Pivot
  • try to change it with reflection
  • move the GameObject
silk tinsel
#

been searching the documentation for something I can use that isn't readonly

#

perhaps I'll have to do it at a rendering level

#

which will not be fun

#

because it needs to be sprite-agnostic

leaden ice
silk tinsel
#

moving the gameObject leads to the desyncing issue

leaden ice
#

I'm not sure I understand the desync issue but I'll take your word for it

silk tinsel
#

basically if I move the gameobject the spriterenderer's gameobject is parented to, any subpixel-motion doesn't apply and so if you move in sub-pixel intervals over time it will desync

#

whoops sorry hit enter early

#

and this needs to support non-zero offsets of the child gameobject with the spriterenderer to the parent gameobject

#

so I can't just use the parent gameObject's position value to calculate the new snapped value

#

I guess theoretically I could introduce a third gameobject into the mix

#

it's not elegant but it might work until I can get under the hood and figure out if I can offset it at some point in the render pipeline

leaden ice
#

Or just a Vector3 to track the sub pixel motion

#

The accumulated sub pixel motion

silk tinsel
#

which is something i'd like to avoid

#

as this is meant to be a project-agnostic system

leaden ice
#

Apply whole number motion to the GO and the remainder to your variable

silk tinsel
#

actually yeah you're right

#

that might work

leaden ice
#

And when the variable accumulates a whole numbers worth you consume that

silk tinsel
#

true I wasn't thinking about it right

#

thank you I will try that

somber nacelle
#

you can probably store them as a Func<IEnumerator> so that you don't start executing any of the coroutine's code until you Dequeue and then invoke it in the StartCoroutine call. I haven't tested this though

silk tinsel
somber nacelle
lament bloom
#

This definitely looks like a valid collision, right?

#

I'm not sure why, but it's just not getting registered

hexed pecan
lament bloom
#

an animation

#

oh i think i know what's going on

#

I'm using OnTriggerExit

#

but sometimes due to the way the animation works

#

the axe's mesh collider is actually disabled before it leaves the player's collider

#

and so the call is never made

hexed pecan
#

I would probably just use physics queries for melee weapons

swift falcon
#

any chance would anyone know why the ui on my hotbar is broken on the second client? its multiplayer and im using mirror, the UI recognizes there is an object there just the sprite doesnt load

cosmic rain
swift falcon
#

the sprites is loaded from a scriptable object

#

this is the second client

#

this is the first

cosmic rain
#

So what's exactly not loaded?๐Ÿค”

#

Also there seem to be 7 errors in the first screenshot

swift falcon
#

there just misc errors unrelated, (footstep audio)

#

in the first pic if you look at the hotbar

#

the sprite isnt there

cosmic rain
#

Where do you add items to the hotbar?

wise kindle
#

hii, can we put collider-related questions here?

swift falcon
#

the bottom row corealates to the hotbar so what ever item is in there the will show in the hotbar

#

its drag and drop

cosmic rain
wise kindle
swift falcon
#

wait

#

ill upload to a file for easier readibilty

#

what website can i upload it to

#

i forgot what its called

cosmic rain
#

!code

tawny elkBOT
#
Posting code

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

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

swift falcon
cosmic rain
#

Ummm... Wat? Where is that even called from?

swift falcon
#

thats called everytime theres a ui change

cosmic rain
#

If you share code, please provide the whole context. If you can't decide what's related, share the whole script.

#

Don't just copy-paste part of a method.

swift falcon
#

one sec ill share the whole script but you did ask where i added objects to the hotbar

cosmic rain
#

Ok, for starters, don't use try catch to handle your ui logic...๐Ÿ˜…

swift falcon
#

alrighty noted ๐Ÿ˜„ haha

cosmic rain
#

Add debugs along your code. Make sure your refresh ui methods is even being called.

#

If it is, then your try catch is probably catching some kind of error. Remove the try catch and instead make proper null checks. Add debugs there as well.

swift falcon
#

alrighty one moment ill try it rn

#

yeah its being called

cosmic rain
#

And fix the other errors or disable the code that generates them. You don't want to go through a bunch of errors looking for the right one...

#

It's blasphemy to keep errors in your console without addressing them.

swift falcon
#

the error is because the footstep audio isnt networked haha so its getting a null reference

cosmic rain
#

Then disable the relevant code.

#

Or are you planing to publish your game with these errors?

#

It doesn't matter what causes the errors. It's not normal to just ignore them.

swift falcon
#

nah i was just going to fix it later as it isnt game break

#

its in my trello todo list for misc stuff to fix

cosmic rain
#

Well, it might get in your way of solving other issues. But suit yourself

swift falcon
#

i got rid of the try catch and added a null check but that still didnt solve the issue unfortunatly

swift falcon
#

so ill just fix the footstep audio at another date

cosmic rain
swift falcon
#

i tried with 3 clients the sprite only shows on 1

cosmic rain
#

Look at where you're adding the items to the slots and makes sure there's no problem there.

swift falcon
#

Yeah the hotbar item is null

cosmic rain
#

Great. Now figure out why it's null. Probably because you're not setting it.

wild warren
#

In the previous week unity made a change in remote config and it messed up all my project,

#

I added obselete to configManager still didn't work

#

I also replaced unity.remoteConfig to unity.services.remoteConfig

#

And configManager to RemoteConfigService.instance

#

Still no luck

#

Am I missing something????

rotund burrow
#

i have an object that needs to overlap sphere around it every update. should i add another collider with a trigger for that? but then the radius and later shape to check will change. right now i have a script that overlaps sphere and filters through the returned array, but it's sloppy.

latent latch
#

Are you asking if overlap is more performative than using colliders*?

#

Technically, a collider will do similar checking over an array with all other colliders in the vicinity, so what you're doing isn't exactly that different from just using a collider. One plus of checking with overlap, you get to control how much it checks for colliders instead of every (fixed?) update.

#

Of course if the game object is small or traveling quickly, you'll want to check as much as possible.

indigo haven
#

Hey good day.
I have this code:

public static IEnumerator BacktrackerRecursivo(Celda[,] laberinto)
    {
        // Stuff
        
        while (pilaVisitados.Count > 0)
        {
            if (GeneradorLaberinto.EjecuccionPorPresion)
            {
                while (!GeneradorLaberinto.EjecutarUnaVez)
                    yield return null;
                GeneradorLaberinto.EjecutarUnaVez = false;
            }
            else
                yield return new WaitForSeconds(0.5f);
            
            // Stuff
        }
    }

This code does stuff but waits for the user to press a key (the condition in the while) before doing each iteration of the while.
I want to know if i can make that if-else into a function becouse i have it repeated in more than 1 method

#

Any advice?

green ice
#

Hi guys,if when i spawn a prefab when game starts i want that when this prefab click a button call a method contained in a script attached at an object in the hiearchy that is there since before the game starts how can i do it?

trim schooner
#

Stop cross posting.

ruby fulcrum
#

is there any way to render a tool (eg a gun) so that it doesnt mesh into walls, but at the same time isnt see-through

#

i used the method where you render it on a seperate camera ontop of the main camera, it worked but theres the issue of the tool being see through

hexed pecan
#

Is that the perspective of your game?

ruby fulcrum
#

yes

#

in run

hexed pecan
#

The dual camera method makes sense for a first person game, not so much for this kinda game

ruby fulcrum
#

oh

hexed pecan
#

I'm not sure what you want it to look like though

ruby fulcrum
#

it meshes like this

hexed pecan
#

So you want to render it on top of walls, but not be seen thru walls

#

Thats contradictory

ruby fulcrum
#

actually i got a better idea

#

ill just use a mesh collider instead

indigo haven
#

How would you make a corrutine wait until the player press a key before continuing?
Like the function does stuff then waits for a key press before continuing doing stuff

mellow sigil
#
yield return new WaitUntil(() => Input.GetKeyDown("space"));
dusk apex
indigo haven
mellow sigil
#

What is a presion?

indigo haven
#

When you press space i mean

mellow sigil
#

What happens then?

indigo haven
#

Two executions of the stuff that should happen once

dusk apex
#

You'll need to provide more context to get better help

mellow sigil
#

well you have the coroutine running twice then

indigo haven
#

Okay i will explain more, sorry for the confusion

trim schooner
dusk apex
indigo haven
#

I have a maze and im making corrutines to be able to show the process of making the empty maze into a proper maze using algorithms.
To do so i have decided to make the algorithm a corrutine and make the iterations of said algorithm wait until the user press space to do a iteration (like, you press space and a cell fo the maze gets build)

#

I have this code:

public static IEnumerator BacktrackerRecursivo(Celda[,] laberinto, Vector2Int posicionInicial)
    {
        // Stuff
        
        while (pilaVisitados.Count > 0)
        {   
            posicionActual = pilaVisitados.Peek();
            laberinto[posicionActual.x, posicionActual.y].EstadoActual = EstadoCeldaEnum.Actual;
            
            if (GeneradorLaberinto.EjecuccionPorPresion)
            {
                
                while (!GeneradorLaberinto.EjecutarUnaVez)
                    yield return null;
                GeneradorLaberinto.EjecutarUnaVez = false;
            }
            else
                yield return new WaitForSeconds(0.5f);
            
            // Stuff
            
        }
    }
#

This works more or less. I can translate if needed but the variables are a static variable to make it execute just once and a condition to see if it must be execute by waiting 0.5 secs or by presing space

trim schooner
orchid bane
#

I don't have method .Schedule() for job, what do I do to get it?

#

I use 2021.3

late lion
orchid bane
late lion
orchid bane
late lion
heady iris
#

show your code

orchid bane
#
[BurstCompile]
    private class FindNearestFoodJob : IJob {
        private readonly Vector3[] _foodPositions;
        private readonly Vector3 _headPosition;
        private NativeArray<Vector3> _nearestTarget;

        public FindNearestFoodJob(Vector3[] foodPositions, Vector3 headPosition, NativeArray<Vector3> nearestTarget) {
            _foodPositions = foodPositions;
            _headPosition = headPosition;
            _nearestTarget = nearestTarget;
        }

        public void Execute() {
            float sqr = float.MaxValue;
            foreach (var foodPosition in _foodPositions)
            {
                float distSqr = (foodPosition - _headPosition).sqrMagnitude;
                if (distSqr < sqr)
                {
                    sqr = distSqr;
                    _nearestTarget[0] = foodPosition;
                }
            }
        }
    }```
#
var job = new FindNearestFoodJob(foodPositions, headPosition, _nearestTargetNative);
        _jobHandle = job.Schedule();```
late lion
#

Your job is a class, not a struct.

orchid bane
#

Oh

#

Thanks

heady iris
#

yeah, I thought that looked a little funny

late lion
orchid bane
#

Should it be like this instead?

var job = new FindNearestFoodJob(new NativeArray<Vector3>(foodPositions, Allocator.Temp), headPosition, _nearestTargetNative);```
late lion
orchid bane
#

Should I dispose of it at the end of the job? (inside)

cosmic rain
#

I don't think that's possible in a job(that would be on the other thread)

orchid bane
#

Where do I do it then?

cosmic rain
#

Create a local variable outside the job and dispose of it later when getting the results of the job.

#

Doesn't have to be local I guess

orchid bane
#

Should I Dispose of it right before giving it a new value then?

cosmic rain
#

Could be mixing up with something else๐Ÿค”

orchid bane
#

Gonna try

late lion
#

You also need to use TempJob or Persistent if you want to pass it into a job.

orchid bane
#

Okay, thanks

swift falcon
#

but idk how to sync it, i cant find any decent references

cosmic rain
swift falcon
#

i want the inventory to be server authorative but again i cant find a single reference ๐Ÿ˜ญ

swift falcon
#

im using mirror haha

cosmic rain
swift falcon
worldly hull
#

my team uses a chaotic setup for backends

#

cant recommend that to u , it gonna ruin ur game

#

somehow it works tho

cosmic rain
hard estuary
# swift falcon im using mirror haha

Back when I used Mirror I used BinaryFormatter to convert data into a byte array, and then sent the data as byte array via ClientRPC. It's not comfy, but it did the job. ๐Ÿค” But it's recommended to avoid BinaryFormatter.

swift falcon
#

what would you recommend for differnet cases for syncing data between server and client?

swift falcon
#

theres more reference material for fishnet to learn off

worldly hull
#

https://www.youtube.com/watch?v=b7urNgLPJiQ
theres already some tutorials showing how to breakdown binary formatter stuff

worldly hull
#

welp, only use it if u know what ur doing

#

and u have the confidence it wont bring ddos or other bad stuff to ur server

swift falcon
#

cant you restrict the amount of data being formatted? so it doesnt cause dos ?

#

fuck i need sleep :/

#

but i wanna finish :/

hard estuary
swift falcon
#

its outdated tho

#

alot of stuff from those series have been made obsolete

cosmic rain
swift falcon
digital fern
#

Hello there, having some thoughts right now on how should i implement my "Game manager script".
Should i :

  1. Make a static class "GameManager" which is never linked to a GameObject and accessed globaly through the engine ?
  2. Make a "GameManager" MonoBehaviour, instantiated in a preload scene, accessed through singleton throughout the game ?
  3. Make a "SpecificSceneManager" MonoBehaviour, instantiated in each scene, accessed only during the specific scene i am and destroy by switching scenes (which are used as "states")
#

Somehow, the [2] options seems the best choice to me

swift falcon
heady iris
#

I usually just make a component that makes itself available via a static field

#

If it needs to survive between scenes, it would get marked DontDestroyOnLoad()

digital fern
heady iris
#

one suggestion: do it more like this

hard estuary
# digital fern Hello there, having some thoughts right now on how should i implement my "Game m...

It kinda depends on what your manager does. Instances of managers are handy in multiplayer games (e.g. you can have a separate manager for every match instance). I suppose instances also could be handy if you wanted the possibility of having several instances accessible at the same time, kinda like tabs in a web browser or project files in Photoshop.

If you're 100% sure you're never gonna need it duplicated, then any solution will do.

MonoBehaviour managers are quite handy if you want to configure them or debug their values in the inspector.

heady iris
#
public class GameController : MonoBehaviour {
  private static GameController _instance;
  public static GameController Instance {
    get {
      if (_instance == null) {
        _instance = FindObjectOfType<GameController>();
      }
      return _instance;
    }
  }
}
#

this lazily initializes the singleton

#

this is useful if you want to have other things find this guy in their own Awake methods

heady iris
#

if it isn't, log a warning that you have two GameControllers

agile tulip
#

Howdy all! I'm trying to remove a outline on a Instantiated object but it's not working. Can anyone spot what I'm doing wrong?

GameObject buildedItem = Instantiate(BuildingMenuItem.newItemModel);
Outline removeOutline = buildedItem.GetComponent<Outline>();
removeOutline.OutlineWidth = 0f;
agile tulip
#

debug log also gives

heady iris
#

is this some kind of custom component? I don't reecognize it

swift falcon
#

so you know its only initalized 1 time

agile tulip
swift falcon
#

i just completely removed mirror from my project and un networked all my scripts and im going to migrate to fishnet as it seems more reliable

thin aurora
heady iris
#

it is a lazily-initialized property

heady iris
#

it's a convention for private fields

thin aurora
#

Also, talking aobut improving the system, I suggest you make sure that there's not multiple instances of the given type

thin aurora
swift falcon
#

ah yes

thin aurora
heady iris
#

ya

thin aurora
#

There's not a whole lot of reason to lazily initialize it, though

heady iris
#

it's a little more code, but it completely avoids problems with ordering

swift falcon
#

whats wrong with just doing what i said tho haha

thin aurora
#

Nothing really

heady iris
#

yeah, it's fine

#

we're bikeshedding here :p

#

you probably shouldn't have singletons trying to talk to each other in Awake

swift falcon
#

fair enough was just wondering haha if theres anything wrong with that lol thats how i normally do it

heady iris
#

so it wouldn't come up anyway

hard estuary
#

This lazy initialization sounds like a good way of avoiding blockers in build, but I would suggest adding a warning log to it so developers will know there were some issues with the initialization order and patch it up later.

digital fern
#

Do you make a difference between game modes and game states ? Or do you implement both using FSM ?

hard estuary
# digital fern Do you make a difference between game modes and game states ? Or do you implemen...

Honestly, it's hard to tell. I suppose in some cases I would go for completely independent scripts and sometimes I would use some kind of FSM. FSM would be great if you can't simply turn off the other game modes, which would allow the player to choose what mode he is using right now (e.g. in the pause menu he shouldn't be able to interact with his game except resuming the game, and during the game, he shouldn't be able to interact with pause menu except entering it, but there is a chance both things will be active at the same time). I suppose FSM would work well for implementing mini-games and such. But there is no need for FSM if every game state is separatable beings, such as levels in games (you can't be at the 2 levels at once).

agile tulip
digital fern
gleaming sparrow
agile tulip
digital fern
agile tulip
gleaming sparrow
#

what is the outline script

#

can u send snippet

digital fern
#

i dont know then

agile tulip
digital fern
#

set is outline mode

agile tulip
#

Well the thing is all code should work but somehow the GameObject buildedItem = Instantiate(BuildingMenuItem.newItemModel); looks like it's not defining the buildedItem

#

If I use it on BuildingMenuItem.newItemModel it's all working

#

But I only want to target the Instantiated object

gleaming sparrow
#

BuildingMenuItem is a static class I assume?

gleaming sparrow
#

yeah makes sense it'd do it for all objects then... hmm

#

maybe u need to add your own custom func to the Outline script to make it happen

agile tulip
#

But it should still be possible to destroy the outline component on the Instantiated object right? :S

fresh widget
#

Anyone here who has ever used Runtime Hierarchy and Inspector? I am having a problem that the text in hierarchy and inspector is not visible anymore when I play my game. Why am I using it? Because I am making an AR game which can't be debugged in editor while playing.

gleaming sparrow
gleaming sparrow
#

what is this BuildingMenuItem class

agile tulip
#

It holds the prefab that is selected to build

gleaming sparrow
#

is it your own class or did it come with the asset

agile tulip
#

my own

gleaming sparrow
#

is buildedItem actually the obj that holds the outline comp? are u sure

#

like not a child of that obj or smthn

steep herald
#

Using FinalIK, some asset from the store, I'm running into issues manually controlling the execution order of the solvers.

In my tests, by accident, I realized that disabling and re-enabling the actual solver components in the order than I want will cause them to execute in that precise order.

I was able to confirm the behaviour with the simple class below. I added 5 instances, enabled them in the order I want and their update order will follow the order in which they were enabled.
e.g.


public class PrintFoo : MonoBehaviour
{
    [SerializeField]
    private string foo;

    private void Update() => print(foo);
}```
Does anybody know if this behaviour can be relied upon? Will this be persistent across platforms?
agile tulip
#

first time I try to target a Instantiated object

gleaming sparrow
#

it should* but does it? need to be certain

agile tulip
gleaming sparrow
#

does buildeditem have any children

agile tulip
#

The outline stays active so

gleaming sparrow
agile tulip
#

GameObject buildedItem = Instantiate(BuildingMenuItem.newItemModel);

gleaming sparrow
#

that doesnt rly answer my question

#

youre instantiating a prefab

#

a prefab can have children

#

can u show me ur buildedItem prefab in the editor

gleaming sparrow
#

oke no children

agile tulip
#

I now see the Outline component isn't part of the prefab, but get's added to it when I click the menuItem

gleaming sparrow
#

i think i see

agile tulip
#

but I think that still wouldn't be the problem?

gleaming sparrow
#

i think it's editing the material and setting it once

#

meaning, the material is permanently edited

#

meaning removing the component wont do anything as it already fulfilled its task

#

is there any way you could confirm this theory?

agile tulip
#

Yeah I can check if the component gets deleted

gleaming sparrow
gleaming sparrow
#

i just think that the material is edited

#

so removing the component after its been edited wont do anything

#

u need to find a way to revert the material to its original

#

maybe u can save a duplicate?

#

do keep in mind that it shouldnt have the same reference, because the material doesnt get changed per-object.

agile tulip
gleaming sparrow
#

it gets changed in its root, so it applies to all objects with that material

#

ahhh

#

its its own material

#

thats good actually

#

u should try grabbing the outline fill and mask materials and remove them from the object

#

if u just manually delete them at runtime, does the outline disappear? if so, then we've found the root of the problem

agile tulip
#

can't change it but it does show some glitching

gleaming sparrow
#

hmm well try to remove those materials with code and i think you should have your solution

#

List<Material> myMaterials = GetComponent<Renderer>().materials.ToList(); and then the first 2 i assume

#

u may need to refresh something afterward to clean up or smthn

kind nymph
#

My question is about Unity Matchmaker. I want to have rival's name when matchmaker responses match id( also ip/port) to each client. I'm using photon fusion and transfer names by using RPC's. But it is too slow to transfer names. I need to show rival's name before being connected to photon. Thanks.

agile tulip
#

The code above gives this error: error CS1061: 'Material[]' does not contain a definition for 'ToList' and no accessible extension method 'ToList' accepting a first argument of type 'Material[]' could be found (are you missing a using directive or an assembly reference?)

heady iris
#

ToList is an extension method added by System.Linq

steel vortex
#

Elevate your workflow with the Low Poly Animated - Modern Guns Pack (URP) asset from Infima Games. Find this & other Animations options on the Unity Asset Store.

Use the FPS Animation Framework tool from KINEMATION on your next project. Find this & more animation tools on the Unity Asset Store.

ember ore
#

Anyone knows what the hell this error means?

#

Or where it comes from?

heady iris
#

what is this a screenshot of?

ember ore
#

It fires them like every second

agile tulip
heady iris
#

the ToString method for a list just spits out the type

agile tulip
thin aurora
cosmic rain
thin aurora
agile tulip
#

myMaterials.RemoveAll(x => x.name == "OutlineMask (Instance) (Instance)"); doesn't work, how should I target the elements?

agile tulip
#
List<Material> myMaterials = buildedItem.GetComponent<Renderer>().materials.ToList();
foreach (var x in myMaterials)
{
  if(x.ToString() == "OutlineMask (Instance) (Instance) (UnityEngine.Material)")
  {
    Destroy(x);
  }
  if (x.ToString() == "OutlineFill (Instance) (Instance) (UnityEngine.Material)")
  {
    Destroy(x);
  }
}
#

Fixed it, thanks all for the help! โœŒ๏ธ

heady iris
#

that's a little scary...

#

you probably just want to check which shader the material has

#
Material mat = // ...
mat.shader == shaderField;
#

where shaderField is a field of type Shader

#

you would assign the shader you want to get rid of

ember ore
#

I have a "Task" object in an synchronized method.
How can i wait for the task to finish? Theres no callback

agile tulip
#

mat = x ?

heady iris
#

just get the material from somewhere

#

was just an example of what you could do

#

in this case, yes, x is a Material

heady iris
#

wouldn't that just be Wait()

#

this will block the thread, of course

agile tulip
heady iris
#

bam, shader field

agile tulip
heady iris
#

you can't just write a name like that

#

public Shader shader will create a field

#

you can then assign a shader to that field.

agile tulip
#

Aaah

heady iris
#

I do believe you can look up a shader by name, but you might as well just assign a reference so that it's guaranteed to be right.

thin aurora
#

I mean, there's probably a better way to check the stuff to remove than their name

heady iris
#

we are improving it

#

yes

thin aurora
#

This just screams prone to error

heady iris
#

that's why we're having the current conversation

#

bonus: you'll be able to write it like this

#
var materialsToDestroy = buildedItem.GetComponent<Renderer>().materials.Where(x => x.shader == shaderToDestroy)
foreach (var mat in materialsToDestroy) {
   Destroy(mat);
}
#

although, this seems a little odd

#

destroying the materials instead of just, say, assigning null into the material slots

#

I guess it works out the same. materials will make unique copies of the materials for that specific renderer

#

so destroying them won't affect anything else

heady iris
knotty cargo
#

I have a settings menu in my game (two separate ones: one for the pause menu and one from the main menu) that can control volume and a few other gameplay settings. What's the best way to handle this? Right now, I have a Settings class that is a singleton and works as a place to store current values so I can reference it from different game objects to use those values. I feel like there's a more conventional method, though..

heady iris
#

sounds reasonable to me!

agile tulip
#
var materialsToDestroy = buildedItem.GetComponent<Renderer>().materials.Where(x => x.shader == checkOutlineFill || x.shader == checkOutlineMask);
                    foreach (var mat in materialsToDestroy)
                    {
                        Destroy(mat);
                    }
#

it is ๐Ÿ’ช

heady iris
#

tada

#

bit of a long line

#

one way to improve that is to put line breaks before the Where

#
foo.GetThings()
   .DoStuff()
   .DoMoreStuff()
   .Microwave();
#

this is a common pattern when using LINQ

#

each operation gets its own line

agile tulip
#

Epic stuff! Thanks for all the help and explanation buddy! ๐Ÿ’ช ๐Ÿ‘Š

heady iris
#

no prob

ember ore
#

Any idea why those artifacts are occuring?

dusk apex
abstract panther
#

hi, i have an isometric tilemap and am trying to allow the user to hover over the tiles and click to select them. however, i have a problem where the tile that my cursor is on is not actually the one that is being selected when i hover. the image shows an example, where the red is the cursor.

        // Get the mouse position in world coordinates
        Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector3Int tilePos = world.WorldToCell(mousePosition);
        tilePos.z = tileZ;

        // Try to get a tile from cell position
        TileBase tile = world.GetTile(tilePos);

here is the code i am using to get the tile that is being hovered over. this code is in LateUpdate. is there an issue here?

abstract panther
#

actually just to make sure, how would i make sure the z is correct

rigid island
#

I think you can see it in the tilemap

abstract panther
#

and here is the inspector

rigid island
#

hmm yeah 0 should work..

abstract panther
rigid island
#

that Z as Y though is sus that could be it maybe, I never used ISO before just hex/squares

abstract panther
#

hmm maybe, ill try making it a not z as y tilemap and then see what happens

#

nice that fixed it

#

thanks @rigid island now its time to figure out why that might have fixed it by first figuring out what z as y means

#

time to spend hours reading unity docs!

rigid island
#

just the way it's laying out the tiles I guess in respect to unity's world coords

abstract panther
#

hmm yeah but im not sure what Z as Y means in particular

#

like i understand that its taking whatever Z is and somehow putting that information in the Y coord, but i dont know how it does that...

rigid island
#

ahh

abstract panther
#

in this case is y the vertical axis? like its going up and down?

rigid island
#

ahh 2d hella confusing xD
i remember the pain of figuring that out with hex tiles, i had to change sort axis into some weird number. It was not fun xD

#

tilemap itself is easy tho

abstract panther
#

yeahh -0.26 lol they are pulling numbers out of their ass

rigid island
#

magic numbers xD

heady iris
#

i presume the value depends on the view angle

abstract panther
#

lmao thank you though, at least i know what makes it work so that i can figure out the rest of the details

abstract panther
heady iris
#

it would be nice if it was a root of something

#

maybe divided by another thing

agile tulip
#

but everything I place on top just uses the normal cords

#

But I'm also really utilise the 3d space and models, don't know if you have it same or you are just using 2d that looks 3d?

abstract panther
#

but yes i am just using 2d that looks like 3d

agile tulip
abstract panther
#

i am using a 2d tilemap, i am not making 3d models and fixing the view as isometric with the camera

abstract panther
agile tulip
#

bottom one Order in Layer

agile tulip
bronze crystal
#

why is my sphere not sticking: ```private void OnCollisionEnter(Collision collision)
{
if (collision.collider.CompareTag("Stickable"))
{
transform.parent = collision.transform;
Debug.Log("sticked");
}
}

private void OnCollisionExit(Collision collision)
{
    if (collision.collider.CompareTag("Stickable"))
    {
        transform.parent = null;
        Debug.Log("unsticked");
    }
}```
desert shard
#

do your logs get printed

hard estuary
bronze crystal
#

foreach (ContactPoint c in playerRigidbody.GetComponent<Collider>().contacts)

#

error CS1061: 'Collider' does not contain a definition for 'contacts' and no accessible extension method 'contacts' accepting a first argument of type 'Collider' could be found (are you missing a using directive or an assembly reference?)

simple egret
#

That line of code cannot report that error

#

Ah, better

#

Contacts can only be fetched from collision callbacks like OnCollisionEnter. Colliders themselves don't have such knowledge of contact points

bronze crystal
#

i try to implement a mechanic

#

where a player can stick on a bigger sphere which rotates

#

and if you push spacebar you jump and you can move free again, no gravity.

west blade
#

working on a full body fps character, what methods are used to keep the camera from shaking around with an animation while parented to the characterโ€™s head?

bronze crystal
#

@simple egret you know why my player keeps bouncing?

#
    {
        if (isSticking)
        {
            // Set velocity to zero
            playerRigidbody.velocity = Vector3.zero;

            // Calculate the offset based on the size of the sticky object's collider
            Vector3 offset = stickyObject.GetComponent<Collider>().bounds.extents.y * Vector3.up;

            // Calculate the player's position relative to the sticky object's rotation
            Vector3 relativePosition = Quaternion.Inverse(stickyObject.rotation) * (transform.position - stickyObject.position);

            // Set the player's position to be just above the sticky object, taking into account the sticky object's rotation
            transform.position = stickyObject.position + stickyObject.rotation * (relativePosition + offset);

            // Disable the player's rigidbody gravity and velocity
            playerRigidbody.useGravity = false;
            playerRigidbody.velocity = Vector3.zero;
        }
        else
        {
            // Enable the player's rigidbody gravity
            playerRigidbody.useGravity = true;
        }
    }```
simple egret
#

Ah that's a question

#

The lack of ? at the end of the sentence made me doubt

#

Anyway, you should not ping specific people into your question as it's a brand new one here

bronze crystal
#

my bad thought you were already answering my previous one

simple egret
#

The previous one yes, that one is a new one

#

But no, I don't know why it bounces. Is execution even reaching into that if statement there? Where you set .velocity = Vector3.zero

#

Canceling out the velocity should probably be done in OnCollisionEnter so it's as fast as possible

serene bridge
#

Does anyone know why the ConcurrentBag.Clear method is not showing up in my Class Library within Visual Studio? I have my Target Framework set to 4.8. If I create a script within Unity the Clear method shows up. Just not in the external class library . . .

#

Nevermind, I guess the frameworks do not have support for the Clear method. I guess I misunderstood the frameworks. I thought you got Standard 2.0 (or 2.1) support plus more features with them, but it looks like Standard actually includes features that the frameworks don't?

soft shard
# west blade working on a full body fps character, what methods are used to keep the camera f...

That may depend on how your character is setup, but generally, you either want to control the position and rotation by code, or attach your camera separate from your bone rig, for example, this is how ive setup mine - the "node" is a container that holds scripts like input, movement, etc but it doesnt move itself, "root" contains colliders and rb, thats the only child that moves, attached to it is a (cinimachine) camera and the animator parent that holds the rig/animations depending on the character I want to spawn, I take it a step further and put the head mesh of the rig on a different layer and make sure the camera does not render that layer to avoid clipping at weird angles and animations

west blade
soft shard
solid rampart
#

Does anybody know how can i access the classes and methods of a module in unity? I'm trying to see how it's used bcs there is no enough documentation

dusk apex
#

Which one in particular?

somber nacelle
west blade
solid rampart
#

And the photo is clear anyway ๐Ÿ˜†

soft shard
soft shard
solid rampart
west blade
soft shard
# west blade i see how i would get that to have the effect of the spine bending for the camer...

Correct, because the rigs spine would be controlled by your animator, unless you use IK overrides to influence the rotation yourself, either setup on your rig (for example, from Blender if you made it there) or theres a Unity IK rig package that uses the Jobs system and some other IK controls to let you still play for example a "breathing idle" animation but also rotate the spine or hand or whatever while that animation plays, im sure there are other IK solutions or git projects as well

west blade
#

I just got IK working to keep my character's hands on their weapon as a test with hopes of going in that direction

soft shard
ocean pewter
#

probably a total noob question but are there curve datatypes we can use outside of animation? For example, scaling floats for character attributes etc. Do people just use animation curves for this or is there some other asset type more suitable?

soft shard
west blade
soft shard
ocean pewter
gloomy mortar
#

@fringe drift

How should I post the code?

ocean pewter
#

Oh I think I have DoTween from some humble bundle ages ago lol Never checked it out. So thats what its for?

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.

soft shard
gloomy mortar
solid rampart
somber nacelle
#

i'd bet you have NullReferenceExceptions in your console that you are ignoring

soft shard
somber nacelle
#

can confirm that DOTween is pretty good. it's also fairly easy to use

fringe drift
ocean pewter
#

and just for the record, you use commas beautifully ๐Ÿ˜‰

quasi lily
#

Following this tutorial to implement third person shooting:

https://www.youtube.com/watch?v=FbM4CkqtOuA&t=14s

๐Ÿ’ฌ How to make a Third Person Shooter Controller in Unity!
โœ… Get the Project Files https://unitycodemonkey.com/video.php?v=FbM4CkqtOuA
๐ŸŒ Get my Complete Courses! โœ… https://unitycodemonkey.com/courses
๐Ÿ‘ Learn to make awesome games step-by-step from start to finish.
๐ŸŽฎ Get my Steam Games https://unitycodemonkey.com/gamebundle

00:00 Third Person Sho...

โ–ถ Play video
#

But getting less than ideal results

#

I think the bullet is colliding with the player when it comes out the weapon but like, I have no idea how to fix that + the player is able to shoot backwards around corners

fringe drift
gloomy mortar
soft shard
# solid rampart I'm referring for the first nameapace for example I'm trying to use a speech rec...

If its a Microsoft namespace or System namespace, you can likely find it on MSDN, if its a Unity-specific package, its probably on the Unity packages documentation (which is separate from the regular class documentation), or you could search through IntelliSense as you type the namespace in a function to see what you can access, and if its documented (which most likely will be) the summary of those functions should give you a good idea of how its meant to be used

fringe drift
gloomy mortar
soft shard
fringe drift
#

You should maybe try to attach it maybe its the problem if it is check the instantiate line/-s

trim rivet
#

Anyone know why this code seems to execute the while loop instantly and ignore the WaitForEndofFrame yield?

#

The parameters are all coming in correctly

simple egret
#

Debugging done? You shouldn't post in multiple channels

trim rivet
#

well yeah, it didn't help me much.

gloomy mortar
# soft shard Awake fires immediately after the script is enabled (assuming the game object it...

hm, currently its not attached to a game object, but is instantiated in a script:

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

public class BattleSystem : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public bool StartBattle()
    {
        BattleManager manager;
        
        string text = manager.AnnouncerText;

        SceneManager.LoadScene("Combat Scene01");

        return true; 
    }
}
trim rivet
#

I'm hoping for somebody to tell me that I misunderstand how while loops work there's definitely something I'm missing

somber nacelle
simple egret
#

The loop is good

simple egret
gloomy mortar
gloomy mortar
trim rivet
simple egret
#

You're not starting it correctly!!!!

trim rivet
#

The stats class then either starts the coroutine if the healthhealduration parameter is > 0, else performs the heal instantly

soft shard
simple egret
#

Oh, please show where the coroutine is started

#

Why would you post another method

desert shard
#

crosposting!?

trim rivet
#

This is where the coroutine gets started

gloomy mortar
#

OK. How do you instantiate a singleton class? I am at a loss rn. It seems the structure of it is correct... but its never instantiated through the awake

somber nacelle
fringe drift
#

With what script do you add the component @gloomy mortar

gloomy mortar
#

No. I wanted to initiate it without adding it to a game object. I will fix that.

simple egret
#

Or even yield return null that delays a frame

trim rivet
#

yeah I have already, same result

gloomy mortar
somber nacelle
gloomy mortar
fringe drift
#

The BattleManager Manager; line is not enough to instantiate a script

simple egret
# trim rivet yeah I have already, same result

Log the value of elapsedTime after you add Time.deltaTime to it. Make sure it's lower than duration after the 1st iteration of the loop. If that's right, then your coroutine might be running multiple times, affecting the variables faster

heady iris
#

this simply declares a field that can contain an instance of that type

#

unfortunately, merely declaring that I have a parking spot for my Ferrari does not cause me to own a Ferrari

gloomy mortar
heady iris
#

Awake runs when a MonoBehaviour is instantiated.

gloomy mortar
#

OK

heady iris
#

(although if it starts out disabled or its gameobject is inactive, then Awake only runs after it becomes enabled)

gloomy mortar
#

Thank you for the help ๐Ÿ˜„ I gotta get used to how unity does things. Prior I did buisness programming for C#.

simple egret
#

You can think of Awake as a sort-of constructor call. It's executed when the object this script is on is created

trim rivet
#

anyway I'll move on to an alternative solution

gloomy mortar
loud stratus
#

Hey, guys! Can someone told me and give me a very detailed explanation of what actually is the serialized field??

heady iris
#

there's not a lot of detail to provide

#

"serialization" is the process of turning an object into data

loud stratus
#

Alright then

heady iris
#

and then "deserialization" is the opposite: data to object

#

a serialized field is one that Unity knows how to turn into data and back again

loud stratus
#

So, for which purposes we are using them?

heady iris
#

if something is serialized, it can be shown in the inspector and is saved in scenes/prefabs

#

by default, only public fields are serialized

#

so [SerializedField] is used to say "i want this to be serialized"

#

even if the field is not public

loud stratus
#

So, it works like public?

desert shard
#

Not really

heady iris
#

i would not think of it that way

#

public is an access modifier. It controls which classes are allowed to see that field.

#

[SerializeField] has no effect on that.

desert shard
#

[SerializeField] is private. but expose it to the unity inspector

loud stratus
#

Is this in advanced programming, I am a beginner and I have not learn it yet

desert shard
#

its hard to explain if you don't know the concept of serialization xD

heady iris
#

you do not need to understand the guts of the system

#

all you really care about is that:

  • public fields get serialized
  • non-public fields with [SerializeField] get serialized
  • only some types are serializable
loud stratus
#

I want to understand just the logic and when I get to that I will learn how to use it

#

Alright

desert shard
#

85% of variables you declare will probably be SerializeField

#

or should be.

loud stratus
#

Can I find it in documentation?

heady iris
#

i'm bad about keeping fields private

loud stratus
#

Why it seems to me very hard to understand and also it seems to be very complex?

#

Do I have to learn all of that

heady iris
#

not really, but you should at least understand why you need to slap [SerializeField] on private fields

#

: so that unity knows to save them

gleaming sparrow
loud stratus
#

Alright, I catch it

loud stratus
heady iris
#

only the class that owns a private field can see it, yes

gloomy mortar
# loud stratus Is this in advanced programming, I am a beginner and I have not learn it yet

OK. Maybe I can help.

Lets take a big picture, right? You see colors, you see a form and you see certain strokes with pen or brush.

Thats the "object", aka an element that is hard-typed and has many attributes attached.

A serialization is the path to make this picture into a generally recognizable string of data, which can be reconstructed to be used again.

It is like a translator from a specific language into a universal one.

heady iris
#

you'll get a compile error if you try to use a member that you don't have access to, and your code editor will not suggest using them

#

(a "member" just being anything attached to a class, like a field or a method)

soft shard
sour zealot
#

im making a multiplayer game using photon and my script is not working, I am getting no errors.

wild pivot
#

this will probably sound dumb but im incredible confused. I manually assign this in the inspector and it works fine. But in builds it doesent seem to work.

Would it make a difference if it was public instead?

wild pivot
#

agh im so confused, for some reason theres a part of my project which just doesent work at all in builds, but works perfectly in editor

dusk apex
wild pivot
#

yea true, alright lemme write this out

knotty sun
wild pivot
#

wheres that? in the build?

knotty sun
#

ffs. google unity log files

sour zealot
wild pivot
knotty sun
#

yes, and a run build will write a player.log file
do you think I am telling you this for the good of my health?

dusk apex
simple egret