#archived-code-general

1 messages ยท Page 326 of 1

lean sail
#

i seriously doubt it, considering the issues you're asking about are like week 1 beginner level. stop wasting your time, get your IDE configured. Then you can see the errors properly

swift falcon
#

๐Ÿ˜ญ

#

Ok ok i will

#

just forget it

#

Ill take help somehwere else

#

I was in a rush rn

#

SO i thought id get some help

knotty sun
swift falcon
lean sail
#

๐Ÿคทโ€โ™‚๏ธ how much of a rush could you be in, that you cant take 10 minutes to setup something that'll point out every error for you. This isnt a rush, you're just being impatient

lean sail
#

Anyways you were warned above by mods, so please stop spamming

swift falcon
#

2 mins

#

actually nvm

#

30 seconds

#

@lean sail@lean sail@lean sail

#

I did it

#

now quick, what do i do

lean sail
swift falcon
#

Ahh wait, now i know whats wrong

#

Honestly the issue isnt with programming knowlegde, i just dont know where to correctly find or how to search the unity methods and function through the docs

dusk apex
#

If your IDE is configured, you ought to get auto suggestions as you type the code that would prevent you ever using invalid or inappropriate statements/keywords

tawny elkBOT
#

:teacher: Unity Learn โ†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

swift falcon
#

No

dusk apex
swift falcon
#

not this again, i have seen this lots of times

#

i just need documentation

#

honestly godot docs are better

swift falcon
#

Will this work

knotty sun
swift falcon
#

what now ๐Ÿ˜ญ

swift falcon
knotty sun
tawny elkBOT
swift falcon
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public Vector3 CameraPosition;
    public GameObject Flower;

    private PlayerMovement PlayerPos;

    // Start is called before the first frame update
    void Start()
    {
        // Initialize PlayerPos in the Start method
        PlayerPos = Flower.GetComponent<PlayerMovement>();

        if (PlayerPos == null)
        {
            Debug.LogError("PlayerMovement component not found on Flower GameObject.");
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (PlayerPos != null)
        {
            CameraPosition.x = PlayerPos.PlayerX - 0.111f;
            CameraPosition.y = PlayerPos.PlayerY + 4.5f;
            CameraPosition.z = PlayerPos.PlayerZ - 3f;

            // Optionally update the camera's actual position
            transform.position = CameraPosition;
        }
    }
}
#
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed = 1f;
    public float smoothTime = 0.1f;
    private Vector3 velocity = Vector3.zero;


    public float PlayerX;
    public float PlayerY;
    public float PlayerZ;


    void Update()
    {
        // Get input from the player
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        // Create a movement vector based on input
        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

        // Apply smooth movement
        Vector3 targetPosition = transform.position + movement * speed * Time.deltaTime;
        transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
    
    
        position();
    
    }


    void position()
    {

        Vector3 position = transform.position;


        PlayerX = position.x;
        PlayerY = position.y;
        PlayerZ = position.z;


    }



}



knotty sun
#

this

PlayerPos = Flower.GetComponent<PlayerMovement>();

uses the Flower game object which is declared as

public GameObject Flower;

which by default is null. So trying to access a null object will throw a Null Ref Exception.
But.. because Flower is public it will be exposed in the Inspector of the script so a reference can be assigned.
You do this by Adding the script to a Game Object and then drag/drop the Flower game object into it's inspector.
This is ALL very basic knowledge if you would spend 1 hour learning

swift falcon
#

ok ok

#

YESSS

#

IT WOKRK

#

I AM A PROGRAMMER

#

Thanks, cya i gtg now

dusky pelican
#

Hello, how can i pass T to action like Action<T>

lean sail
raven yoke
#

Hello, I'm trying to export animations (.anim files) with the UnityGLTF Plugin but the exported files only contain file info but no animation data. Could anyone help me?

#

IDK if Export context is missing some parameters or if I'm missing a step or something else is wrong

dusky pelican
fleet tide
#

My question is more general but i would like have you opinion about it

I use Atavism (Its an MMORPG maker) , its very usefull for some part of an MMORPG cause many thing is already done (Server, guild, PNG,...) but somes things is useless for me and i need to add many specifics thing (Like armor creation).
The real problem is Atavism is so complex and have so many thing that i'm lost for add some thing

Do you think use Atavism for my projet is usefull or useless ?
I use it mainly for the server aspect. I dont have any experience about it and so many people say its very difficult.

leaden ice
lean sail
dusky pelican
#

I want to create a system like this:
When a player produces a gun in a machine, the machine will invoke OnExpGained (classic gun names like usp). Then, in GetExpCount<T>(T expType), it will take the parameter and access usp.GunCategory, which will give me the category of the gun.
With the category of the gun, I can access the public Dictionary<GunCategory, int> GunExpPoints => gunExpPoints; to get the amount of gained experience.

The reason for using <T> is that I need to use the same system in the Quest System. When a player completes a quest, I will invoke an action again like OnExpGained (an upgraded quest).

I might be thinking incorrectly, sorry for the poor explanation, I am not good at it.

lean sail
#

Using a generic static action is definitely questionable, I wasnt even aware you could have one because well not sure where you would provide the type

#

Getting the xp itself as well doesnt seem too related to the action. I would expect this action is invoked after you gain a certain amount of xp. In which case itd make sense to have it be Action<int> and you could possibly include a paramter for the interface, so you also pass in what gave the xp

dusky pelican
#

I will try, thank you so much for your help ๐Ÿ™‚

gray mural
fleet tide
mossy snow
latent latch
#

flabby birb first, mmo later

fleet tide
#

And I'm not here for create a game in 1 week or month , but with my friend we want create it even if it's take many years , we just like it

fleet tide
cosmic rain
timber sierra
#

Hi @lofty siren
I'm a developer of UModeler. This issue can be resolved by hot reloading your project. We will also address this issue to ensure it doesn't occur in the future.

cosmic rain
fleet tide
knotty sun
#

It's absolutely possible for even 1 person to do server side, if that person has sufficient knowledge and experience which is what, I believe, the others are telling you

cosmic rain
#

As for the asset, I'd avoid it for something as critical as server side logic.

#

Btw, you seem to misunderstand something, but MMORPG implies that most of the game logic is on the server side.

#

The client only renders the game and sends the input to the server.

fleet tide
#

I can't create a rpg and after transform it into mmo ? That's what I wanted to do if we create everything

cosmic rain
#

You could reuse some system maybe. If you create them extendable enough

fleet tide
#

In fact , I know its difficult and more for us who don't have many experiences into mmo but I don't think it's a bad idea to just go and start the project and learn even if we need to work during 5 years

The only thing it was just about basic question before start

So if I follow you all , we can but it will be very difficult and long to have something correct ?

nimble cloud
#

so @steady moat as per the conversation in the other channel, i should use the scriptable objects to store data like what resources the items in my game can break down into, and just create game objects and inventory system without using scriptable objects so the game can be saved in a jason format?

steady moat
nimble cloud
#

cool been trying to figure out how to store the date for my crafting system i wanna try to make so this should help.

cosmic rain
cosmic rain
fleet tide
#

it's same for every game ^^'

#

i have already have this thing in my old game

gusty aurora
#

How do I search all VFX graphs in my project ?

heady iris
#

in the project window, you can search like this

#

t:TheTypeYouWant

#

i forget the exact name of a vfx graph asset

#

ah, there it is

#

t:visualeffectasset

#

You can do the same kind of search in the Hierarchy to look for components (not with a Visual Effect Asset, of course, because those aren't components!)

gusty aurora
#

Thanks !

#

How did you find that name ?

heady iris
#

When you click on an asset, the type name appears in parentheses in the inspector

#

It can get a little more complicated for importers.

#

In this case, the inspector is configuring a DataImporter. The resulting main asset is an AttributeMetadata

#

the SVGImporter is producing a Texture2D

#

(you can only search for the actual asset, not the importer that happened to produce it)

gusty aurora
#

I think I got it, thanks !

#

Basically the think inside the first parentheses, without spaces

heady iris
#

yeah, and it's usually just the only thing in parens

gleaming brook
#

man its fun to code ๐Ÿ˜‚ unity is kool

lunar kestrel
#

I want to make a game with different scenes and it would be good that I can keep Player and different stuff between scenes such as game manager and cinemachine camera, should I make all of these GameObjects singletons and add them to don't destroy on load or what? Also in each scene for testing purposes there should be player and all of the other stuff but when I play test from the main menu scene, they should be removed and the original ones would be kept.
Is it good approach to this problem or not?

spring creek
# lunar kestrel I want to make a game with different scenes and it would be good that I can keep...

You do not have to make then singletons for them to be in DDOL.
Also, there is additive scene loading too, which is basically what DDOL is, but you can have more than just that one extra scene.

You could also save the DATA from the player between scenes (in ddol or additive, likely in a singelton for this one), and rebuild the player and stuff in the next scene from that.

Those are the two common methods

tough obsidian
#

i am creating a quiz game using resources.load to change the sprite of questions it is working in the editor but it is not working in the build any suggestions why it is happening? i have tried using asset.database too but same behavior was showing

tawny elkBOT
stoic ledge
#

Are there any out-of-the-box solutions for handling soft keyboard obstructing an input field on mobile?

lunar kestrel
spring creek
#

Have the player added by one scene that you don't return to, then pushed into ddol
Or have it reside in an additive scene only

lunar kestrel
spring creek
lunar kestrel
crisp minnow
#

If I have a bottom bar of a few scenes that I switch between them what's the recommended way to open the other async and close the current once its loaded, setting the next one as active?

spring creek
lunar kestrel
stoic ledge
smoky moss
#

Hey peeps, I'm having a problem with my animator not doing the SetTrigger command, even though the animator is set up properly and everything. I have the same code working in other scripts of my game, but for some reason this animator just doesn't seem to want to trigger. I have confirmed that my animations are working, when clicking inside the Animator window on Unity, so I'm a little stumped as to what is going on here. Help?

heady iris
#

have you checked that your code is running at all?

#

a Debug.Log statement immediately before you set the trigger would be appropriate

smoky moss
#

I have confirmed that the code is running, and that Debug.Log does infact print something out to the console

heady iris
#

a log statement immediately before the SetTrigger, right?

smoky moss
#

Right

heady iris
#

show me your code, plus the animator's parameter list

smoky moss
#

There are no errors when running the code.

#

It is tied to a gameobject in the scene

heady iris
#

Is it targeting the correct Animator component?

smoky moss
#

There are no other animator components on this object, but it does reference SpriteSwitcher, which as its own private Animator tied to it.

#

Can this interfere somehow?

#

I have tried changing the naming on the animator tied to SpriteController, to no avail.

heady iris
#

animator = GetComponent<Animator>();

As long as there is only one animator component on the same object, this will find that component.

#

(and I think you're only allowed to have one per object anyway)

smoky moss
#

The object in question does have two scripts attached to it, both of which has a private animator.

heady iris
#

also, one more sanity check

#

wait, there's no GetTrigger

#

bah

#

just to rule out any weirdness with the wrong animator, you can do this

#
Debug.Log("my animator: " + animator, animator);
#

The second argument is the context for the log entry

#

clicking once on the log entry will take you to the context object

#

(so it'll highlight the object the animator is on)

smoky moss
#

Alright will try that out!

#

It creates a clone of the prefab, which should in theory be fine right?

heady iris
#

Yes, since SpriteController's Awake method runs immediately after instantiation

#

so it will find the animator on the newly created object

smoky moss
#

Perhaps it's because the clone is not spawned as a child of the object, and puts it somewhere else?

heady iris
#

what is "the object" here?

smoky moss
#

The object is basically just an image, I'm trying to write my own visual novel.

#

Upon further inspection I can see that the alpha of the canvas group does change when moved to a child of George, but it does not change the appearance in the scene.

#

The George Clone spawns in with an alpha of 2, which is odd, but it still doesn't change the fact that nothing seems to be happening in the scene.

nova glen
#

Good morning, I am looking for a programmer to create a project together

tawny elkBOT
smoky moss
heady iris
#

what was it?

smoky moss
#

The canvas and triggers did turn out to function normally, but the picture was spawned in way of screen so you'd have no way of knowing it was there. I looked at the scene editor while running the game and found him by zooming out. Adjusting the x values did the trick. I feel immensely stupid.

ember sandal
#

why is 2022.3 so slow ๐Ÿ˜ญ

heady iris
#

did you seriously change your username and profile to "unity is slow"

#

this is not a code question, and it's also barely a question

shell scarab
ember sandal
naive swallow
#

I am trying to making a Bounds object that encapsulates several colliders, but collider.bounds seems to be returning the bounds as if the collider were at zero rotation. How can I encapsulate the bounds of a collider at their current world orientation? If there's a tall thin collider that is laying on its side, I want the resulting bounds to be wide instead of tall.

heady iris
#

That doesn't sound right: collider.bounds is a world-space axis-aligned bounding box

#

I'd expect it to work correctly for a 90 degree rotation, at least

#

there's no collider.localBounds like there is for Renderer, which would behave like that

#

I wonder if you're doing this:

#
  • Instantiate object
  • Update its transform
  • Grab the bounds of its colliders
#

If so, you need to do a Physics.SyncTransforms() first

#

I've seen that problem a few times. The physics system does not notice the changed transform until the next physics update.

naive swallow
#

That's a possibility, let me make a quick toy case to try to test it and see if that's what's happening

#

Okay, you might be right. I just ran a test with some manually rotated colliders and it is properly including them all, even at non-axis'd rotations

#

Lemme try the sync transforms

#

Okay, the colliders are now properly encapsulated. Bad news: A lot of my math was based on the un-sync'd positions so they're hella offset. Going to have to fix all that

heady iris
#

woops

#

You could map between the "old" and "new" positions by calculating a Matrix4x4 to go between them, but I guess it'd be wiser to just update the math :p

#

!collab

tawny elkBOT
golden zealot
#

K ty

pulsar holly
rigid island
#

also this code is painful lol

gray mural
# rigid island also this code is painful lol

No way ๐Ÿ˜ญ

if (other.gameObject.layer == 4)
{
    pieceRotate = false;
    pieceFall = false;
}

if (other.gameObject.layer == 5)
{
    pieceRotate = false;
    pieceFall = false;
}

if (other.gameObject.layer == 6)
{
    pieceRotate = false;
    pieceFall = false;
}
lean sail
#

You guys havent seen their other script. This is actually better than I expected

gray mural
#

Where is the other one?

spring creek
# gray mural Where is the other one?

You'd have to search for it. It was this script, but we all took turns rewriting and suggesting refactors for it.
It was wild at first.
Things like
if(something){line};if(something){line}
Just all crammed in so tight

lean sail
rigid island
#

they should at least be else if

pulsar holly
rigid island
#

all of the != at the bottom will override the values anyway

#

since guaranteed at least one isnt something

pulsar holly
#

The layer of the other gameObject isn't supposed to change, the tag is.

pulsar holly
hard briar
#

hello

pulsar holly
#

Also sorry for sending the message twice, I forgot to ping.

spring creek
pulsar holly
lean sail
pulsar holly
#

I was looking in inspector...

spring creek
#

Add the values to a debug log. (Or learn how to use the debugger)

The inspector is less than useless for this process

pulsar holly
#

I need to run some tests

#

Appearantley it's not detecting the collison hitbox.

vapid imp
#

like a MeshLayer named whatIsGround I have my attempt in the code but it does not work

onyx saddle
#

Does anyone what steps I should take to make a randomly generated force directed planar graph?

sterile reef
#

hello chat
i have a large grid of hexagon that is going act like a map, the goal is to have data assigned to each hexagon.
problem, there are going to be a lot of hexagons (around 100k eventually, maybe more)
how would i approach this, my first thought was to have a single class in the game manager that stores a property class for each tile. this way i dont have 100k+ mono's.

#

anyone care to think with me

heady iris
#

that's a tall order

leaden ice
#

You'll want a chunk loading system aka world streaming

sterile reef
#

hmm, would that work in a grand strategy like game

heady iris
#

why do you need so many tiles?

#

that sounds impossible to deal with as a player

#

maybe you need to have a smaller number of "major" tiles that contain "minor" tiles

sterile reef
#

multiple tiles will be assinged to areas.

#

and areas to provinces

#

and provines to owners[]

#

its for the detail

heady iris
#

i just have to wonder if you need 100,000 distinct hex tiles to make the game work

#

surely the player is not going to go around and inspect all of them!

leaden ice
sterile reef
#

correct

#

also, the tiles will probalbly not contain any data themselves

heady iris
sterile reef
#

i wonder if something exists thats essentially an object that i can detect with mouse input but isnt as heavy as an gameobject

heady iris
#

That would be pretty easy.

#

in fact, Grid can do that for you

#

you can turn a world position into a grid cell

#

go from screen-space to world-space to grid-space

sterile reef
#

also, in my generator i create the faces of the hexagon which is used when creating the gameobject itself

#

if this info is any useful

heady iris
#

You could then store a huge dictionary of positions to cell data

sterile reef
#

cause generating a 50x50 already takes a few seconds (4)

leaden ice
#

That's the easy part

heady iris
#

If you are doing a big complex hex-grid system, you might want to look at...

#

this is mostly for the actual model generation

#

it might help you there

sterile reef
#

thanks!

#

i will look into it

glass chasm
#

I uploaded a minecraft model from blender to unity and it doesnt want to show me the first layer of the skin and i dont understand it

#

i mean anything i press it either becomes translucent or one color

latent latch
#

Not a coding question. Use #๐Ÿ’ปโ”ƒunity-talk for import questions, but the issue you may be having is material incompatibility or maybe not importing correctly.

#

Better to expand out your question in the right channel with perhaps a screenshot

glass chasm
#

thank you

#

and sry

dull barn
#

im using a 3d movement package from the asset store and it hides whatever youre holding when you get too close to a wall to avoid your item clipping through it. Problem is that the script detects the player as a wall if you jump backwards and it will hide and show the item constantly, like making it flash almost. How can i fix this?

#

this is the code that hies the weapon

#

if(WallDistance != Physics.Raycast(GetComponentInChildren<Camera>().transform.position, transform.TransformDirection(Vector3.forward), out ObjectCheck, HideDistance, LayerMaskInt) && CanHideDistanceWall)
{
WallDistance = Physics.Raycast(GetComponentInChildren<Camera>().transform.position, transform.TransformDirection(Vector3.forward), out ObjectCheck, HideDistance, LayerMaskInt);
Items.ani.SetBool("Hide", WallDistance);
Items.DefiniteHide = WallDistance;
}

knotty sun
heady iris
#

sounds like you need to configure LayerMaskInt

knotty sun
#

if that is any example of the code quality, Id say, find another asset

heady iris
#

the repeated GetComponentInChildren calls are certainly a design decision

knotty sun
#

not to mention the completely unnecessay repeated Raycast

lean sail
#

A bunch of paid assets are complete garbage. Worst part is you cant really even know without paying, and once you download the code theres no going back.
If you have to edit it for something like this, I'd go as far as just making your own version. Without looking through every single aspect of it, you wont know what other garbage its doing. Once had an AI asset that allocated like a new array of 1000 elements every frame

sterile reef
#
public void GenerateGrid()
 {
     for (int y = 0; y < gridSize.y; y++)
     {
         for (int x  = 0; x < gridSize.x; x++)
         {
             GameObject tile = new GameObject($"Hex {x},{y}", typeof(HexRenderer));
             tile.transform.position = GetPositionForHexFromCoordinte(new Vector2Int(x, y));

             HexRenderer hexRenderer = tile.GetComponent<HexRenderer>();
             hexRenderer.innerSize = innerSize;
             hexRenderer.outerSize = outerSize;
             hexRenderer.height = height;
             hexRenderer.isFlatTop = isFlatTop;

             hexRenderer.GetComponent<Renderer>().material = material;
             hexRenderer.DrawMesh();

             tile.transform.SetParent(parent, true);

         }
     }
 }

this is the code for generating the grid. any remark on this? i feel like the 2 get components are causing most of my issues

#

ok i see

#

rework time

sterile reef
#

alright, i think i did it,

GameObject tile = GameObject.CreatePrimitive(PrimitiveType.Sphere);
tile.GetComponent<MeshFilter>().mesh = meshRef;
tile.name = $"Hex_{x}_{y}";
tile.transform.position = GetPositionForHexFromCoordinte(new Vector2Int(x, y));

tile.transform.SetParent(parent, true);

i made a private far that stores a single mesh (meshRef)
then i spawn in a sphere and change its mesh

i can generate a 500x500 (250.000 total) tiles within like 4 seconds

#

i think those are decent times

#

if im going to use grid (component) as selection, then i can probably spawn an empty and add a mesh to it right?

#

although

#

that would be a lot of add/get

#

ohoh

#

it crashed loo

devout nimbus
#

When the animator is active the pathfinding on a unit will not work for some reason. The animation contains no keyframes that change positon or rotation. The animator component also does not have root motion enabled. I even got rid of the animation entirely and it still doesnt work. The pathfinding/movement works as soon as I disable the animator tho.

fallen lotus
#

Does anyone know why the position isn't being set?

I have a C# event in PlayerMovement.cs

public static event Action<ulong, Transform> OnPlayerSpawned;

public override void OnNetworkSpawn()
{
    Debug.Log($"Player #{OwnerClientId} has spawned in.");

    if(IsLocalPlayer) {
        OnPlayerSpawned?.Invoke(OwnerClientId, transform);
    }
}

then inside of DevelopmentPlayerSpawner.cs:

public Transform[] playerSpawnPositions;

void Start()
{
    Debug.Log("Test");
    PlayerMovement.OnPlayerSpawned += SpawnPlayer;
}

private void SpawnPlayer(ulong playerNum, Transform player) {
    Debug.Log("Test 2");
    player.position = playerSpawnPositions[playerNum].position;
}

The console is correctly logging "Test" and "Test 2" but the position of the player isn't changing. It is also not logging any errors?

dawn nebula
#

Anyone got experience with DoTween? Is there any way to tween to a moving position?

plucky inlet
fallen lotus
naive swallow
fallen lotus
plucky inlet
fallen lotus
#

i am redoing my playercontroller to use character controller instead of rigidbody

naive swallow
# fallen lotus oh yes it does ๐Ÿ˜จ

CharacterControllers don't like being teleported, they'll snap back to where they were. You can either disable the CC and re-enable it after the teleport, or you can call Physics.SyncTransforms() after the teleport which'll cause every collider to recheck its position and fix itself

fallen lotus
#

Which do you reccomend?

naive swallow
#

Probably SyncTransforms unless it gives you noticeable lag

fallen lotus
#

yay that worked

#

thank you i apprecite you!

earnest pawn
#
> public class EnemyMovement : MonoBehaviour
> {
>     [Header("References")]
>     [SerializeField] private Rigidbody2D rb;
> 
>     [Header("Attributes")]
>     [SerializeField] private float moveSpeed = 2f;
> 
>     //The point we want to move to
>     private Transform target;
>     private int pathIndex = 0;
> 
>     private void Start()
>     {
>         //On start make sure our target point is the first point in the array
>         target = LevelManager.main.path[pathIndex];
>     }
> 
>     private void Update()
>     {
>         //If we have reached the current target (within a margin), advance the index to the next target
>         if(Vector2.Distance(target.position, transform.position) <= 0.1f)
>         {
>             transform.position = target.position;
>             rb.velocity.Set(0f, 0f);
>             pathIndex++;
>             
> 
> 
>             //If we have reached the end of the path, destroy self
>             if (pathIndex == LevelManager.main.path.Length)
>             {
>                 Destroy(gameObject);
>                 return;
>             }
>             else
>             {
>                 target = LevelManager.main.path[pathIndex];
>             }
>         }
> 
>     }
> 
>     private void FixedUpdate()
>     {
> 
>         Vector2 direction = (target.position - transform.position);
>         direction.Normalize();
>         
>         rb.velocity = direction * moveSpeed;
> 
> 
>     }
> 
> }
> ```
#

I have this code for a tower defense enemy moving between points on the map, but for some reason on the x direction it moves in an arc but not on the y. Any ideas on why?

plucky inlet
#

!code

tawny elkBOT
earnest pawn
torpid depot
#

guys ฤฑ need resources for learn quest system

#

anyone have any advice?

#

my englฤฑsh not very well so ฤฑ need a clean resources

earnest pawn
plucky inlet
#

you could try to draw a debug line to show your direction and also the velocity to be sure, they fit your desired values

earnest pawn
split junco
#

How do I a specific object when I am dynamically creating a bunch of gameObjects from a prefab. Here's an example:

I have a prefab that consists of Slider and Buttons. A UIManager instantiates bunch of gameObjects at runtime. I need a way for buttons to get the information of Slider Value. Usually, I'd use something like, transform.find() but that only searches for child gameObjects which is not the case here. I can't do GameObject.Find() because similar objects (and name) for each of the dynamically created objects. Any suggestions?

plucky inlet
solemn raven
#

hey,
I wanna ask about that concept that I'm not sure if it's correct.
is it true that all fps games doesnt really shoot from the weapon but the raycast is fired from the camera ?

vagrant blade
#

You can't claim all, but most do, yes.

#

The player expects the bullet to go where they're pointing. Unless you're making some realism shooter, I suppose, where hip firing is a thing.

earnest pawn
serene stag
solemn raven
vagrant blade
#

Most bullets aren't actually bullets. They're just muzzle flashes with some impact particles wherever the ray hits.

Again, unless you're making a realism shooter and have to use ballistics and firing from the gun.

You have to define what game you're making first to really know what approach you should be taking.

solemn raven
foggy garnet
#

I don't know if this is the right place for this but here goes , i came here to ask for help , i would need someone who could help me to extract the 3d file and the texture of pokemon duel i would need it to print a chess game for a friend , sorry if my english is not perfect i don't master it at 100%.

somber nacelle
foggy garnet
#

๐Ÿฅฒ I'm sorry, I didn't know we weren't allowed to do that.

earnest pawn
serene stag
heady iris
#

that doesn't make any sense

#

a sphere can still move in a straight line

#

It's probably moving in an arc because you have gravity enabled on the rigidbody

#

so it's getting pulled downwards

heady iris
#

Turn off gravity on your rigidbody

heady iris
#

hence the arc

heady iris
#

I've done this before -- you can make the gun point at whatever you're aiming at, but this can cause problems for the player

earnest pawn
heady iris
#

Yeah.

#

The 3D Rigidbody just has a checkbox; 2D gets a scale!

heady iris
earnest pawn
#

thank you so much that worked

heady iris
#

You could also make the rigidbody kinematic

#

That would be appropriate if you're just setting its velocity every frame

serene stag
heady iris
#

A kinematic rigidbody isn't really affected by physics. You just tell it how to move.

tacit copper
#

Should I be using events anywhere I can? Are there any drawbacks to doing this? I'm making a mobile puzzle game if that helps

heady iris
#

Subscribing or unsubscribing creates garbage

#

so you should be careful with, say, subscribing and unsubscribing many times per frame

#

Otherwise, events are very helpful for decoupling your code

#

But they can make it harder to understand what's going on

#

you no longer have explicit function calls connecting point A and point B

tacit copper
#

I'm not firing them every frame, just if something changes on screen or the player presses a button, stuff like that

heady iris
#

Not invoking! That's different.

#

I'm talking about subscribing and unsubscribing

tacit copper
#

invoking, yes

#

ah

#

yeah only on enable and disable

#

nowhere else

#

I'm using a singleton event manager that holds a bunch of public methods that invoke my events

#

not sure if that's best practice but it makes it fairly simple for a relatively small game

plucky inlet
#

Just using delegates and events for updating states is totally fine. Especially if things persist and you just need to update them

soft shard
twin widget
#

guys, i suddenly have some weird bug. the scene manager only works if i load my game from a specific scene, wtf?

vivid halo
#

How do you guys handle player movement sticking temporarily to a wall when you just want the player to fall, but frictionless materials aren't working? My player is being moved with Rigidbody.Move()

leaden ice
#

Your code is telling it exactly where to move

#

Also MovePosition goes through walls

vivid halo
#

Hm, I thought it was different from Transform.Translate

#

in that MovePosition was supposed to check for collisions

leaden ice
#

Not really.

Move with velocity or forces

leaden ice
vivid halo
#

I tried using velocity initially but found it to be unresponsive. Do you think it's the ideal approach?

#

As in, changing direction from forward to backward or left to right felt choppy and not snappy, and increasing velocity / reducing drag and other factors seemed ineffective in addressing this. Any tips for succeeding in this?

waxen blade
#

There's an issue associated with using an equal comparison for transform.position, sometimes even when the transform.position matches the target position, it still says it's not a match. Therefore, to work around this I am using a less tradition methodlogy to move my gameobjects to specific locations:

    public IEnumerator PopUp(NumPadSlotData numPadSlot)
    {
        Vector3 targetPosition;
        GameObject platform;
        float speed;
        float diff;

        platform = numPadSlot.Platform;
        targetPosition = numPadSlot.HighestPlatformPosition;

        speed = Difficulty.MovementSpeed;

        diff = Mathf.Abs(platform.transform.position.sqrMagnitude - targetPosition.sqrMagnitude);

        while (diff > .001)
        {
            // Move one step toward the target at our given speed.
            platform.transform.position = Vector3.MoveTowards(
                      platform.transform.position,
                      targetPosition,
                      speed * Time.deltaTime
                 );
            // Wait one frame then resume the loop.
            diff = Mathf.Abs(platform.transform.position.sqrMagnitude - targetPosition.sqrMagnitude);
        }
        Debug.LogWarning("Platform " + numPadSlot.Digit + " reached destination. platform.transform.position = " + platform.transform.position.ToString() + "TARGET POSITION IS " + targetPosition.ToString() + "DIFF is " + diff);
        yield return null;
    }

This hasn't failed me before when I've used it in another methods. But for some reason, it appears the calculation on Mathf.Abs is failing me. Even though Y is 1f away from my game object, diff claims to be larger than .001 so it's breaking out of the while loop. But according to my logs, it should not be breaking out of the while loop. In the screenshot, platform 8 failed but platform 4 worked with the same method. It's not always platform 8 though.

#

The position of platform 8 has a negative Y value, and the target position has a positive Y value.

#

I need help figuring out why it's breaking out of the while loop even though it hasn't reached the targetPosition yet.

leaden ice
waxen blade
candid pasture
#

How can I get the world coordinates of these corners?

waxen blade
#

I have to get going, this will be a problem I'll deal with later. Thanks PraetorBlue.

dawn nebula
#

Is there a way to get TextMeshPro to work with a Sprite Mask?

latent latch
dull barn
dull barn
lean sail
dull barn
#

okay, but I managed to fix it ๐Ÿ‘

maiden fractal
maiden fractal
green wharf
#

unity game kit's animation doesn't work in my project how can i fix this

#

i can't change the animation type

cosmic rain
green wharf
cosmic rain
green wharf
#

no

#

thats all

cosmic rain
#

And it still says that errors found?

green wharf
#

yes

cosmic rain
green wharf
#

yes the ellen character

cosmic rain
green wharf
#

no

#

xbot

#

imported from mixamo

cosmic rain
#

Is it the Character avatar?

#

Is that the xbot avatar?

green wharf
#

yes its

cosmic rain
#

Well, then that's not how it works.

green wharf
cosmic rain
#

The animation needs to use the avatar that has the same rig that the animation was created for

#

If it's a humanoid avatar, you can also use the same animation with different avatars. But the avatar in the import settings needs to be from the original rig.

green wharf
#

but i can't find animation suitable for my game ๐Ÿ˜ญ

cosmic rain
#

Is this animation not suitable?

#

I think you're misunderstanding my message. Try reading it again

green wharf
#

yes but its not suitable with other animations i downloaded from mixamo

cosmic rain
#

You want to use this animation, right?

green wharf
#

i think i didn't understand

#

i do

cosmic rain
#

Then set it up properly.

#

In fact it was probably set up properly from the start.

#

It needs to either create avatar from the animation rig, or reuse an avatar generated from the same rig.

tawdry tulip
#

Hey guys, anyone could help me on this problem i can't figure it out ...
Why is my ball not bouncing ? she has a physics 2D with 0 friction and 2 bounciness, and the wall have a friction set to 0

knotty sun
tawny elkBOT
tawdry tulip
# knotty sun you are going to need to post your !code

the only code i have is this one which give the ball a random upward direction


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


public class ball : MonoBehaviour
{
    private Rigidbody2D rb;
    

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();

        
        float speed = Random.Range(1f, 2f);

        
        float angle = Random.Range(-45f, 45f);

        
        float radians = angle * Mathf.Deg2Rad;
        Vector2 direction = new Vector2(Mathf.Sin(radians), Mathf.Cos(radians)).normalized;

        
        rb.velocity = direction * speed;
    }

    
}

#

it looks like the ball roll on the wall and when it leaves it the bounce appear

knotty sun
#

I would suggest you debug your direction to make sure it contains what you think it does

serene stag
tawdry tulip
serene stag
#

i think there is no collider on the red and just for bounce there are predefined materials for bounce. did nobody told you.

#

predefined in unity standard assets.

green wharf
#

@cosmic rain copy from another avatar gives error

#

should i edit the names?

cosmic rain
green wharf
#

yes

#

xbot's avatar

#

not ellen

cosmic rain
#

Is that an animation from mixamo?

green wharf
#

yes its

cosmic rain
#

Okay

#

Does it work if you create the avatar from the animation rig?

green wharf
#

no already tried

serene stag
cosmic rain
green wharf
#

i want to use the animation in the unity game kit in my own game

green wharf
#

but the animations don't work

cosmic rain
green wharf
#

yes

cosmic rain
#

Can you take a screenshot of the whole thing?

#

Of the whole inspector, with the error.

green wharf
cosmic rain
#

Ok. So the import is not failing

#

So it should be working.
Also, I just noticed, but this is the coding channel and your issue is unrelated to it.

green wharf
cosmic rain
#

Yes.

green wharf
cosmic rain
green wharf
#

thanks

serene stag
serene stag
#

it will not work then.

cosmic rain
#

It will work if both of the rigs are humanoid. That's what animation retargeting is for.

#

But this is not a topic for this channel

cunning thunder
#

Question: when does canvas update it's position exactly if it is set to screen space - camera?

#

Is it before / after some specifc unity even function?

cosmic rain
cunning thunder
#

just by moving the character around

#

clearly the rect transform (of canvas) changed

cosmic rain
#

I think it's more of a visual cue for debugging purposes. It probably is just using the transformation matrix relative to camera during it's rendering.

cunning thunder
#

ok

leaden ice
swift falcon
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour
{

    public Transform Player;
    public Vector3 OffSet;
    public float t=1f;
    Vector3 velocity;
    

    void FixedUpdate()
    {

        Vector3 target = Player.position + OffSet;
        Vector3 lerpedPosition = Vector3.SmoothDamp(transform.position, target, ref velocity, t);
        transform.position = lerpedPosition;
        transform.LookAt(Player.transform.position);

    }
}

is there anyone knows why my character glitching in the air when im jumping? Here is the code for my Camera Follow.

knotty sun
#

because you are setting transforms in FixedUpdate

swift falcon
#

all right but when I'm changing to LateUpdate still my screen is shaking a little bit

knotty sun
#

should be in Update

swift falcon
#

but it's for camera follow. Shouldn't be in LateUpdate or FixedUpdate?

#

Yeah same result for Update too

knotty sun
#

nah

#

not even sure what you are expecting the lerp to do

swift falcon
#

I used SmoothDamp, i used lerp first. So don't mind the parameter name

knotty sun
serene stag
#

ok steve but luna did you tried this.

#

float newPosition = Mathf.SmoothDamp(transform.position.y, target.position.y, ref yVelocity, smoothTime);
transform.position = new Vector3(transform.position.x, newPosition, transform.position.z);

swift falcon
#

let me try it

#

should I try it in LateUpdate?

serene stag
#

yea try it and see.

swift falcon
#

it's work really good but i when move middle of air, still screen shaking a little bit

#

LateUpdate

#

i tried but it didnt work so ill see what can I do. Maybe there is another problem at somewhere else

cosmic rain
#

That's why fixing one thing doesn't fix the whole issue.

swift falcon
#

rigidbody

leaden ice
#

Did you forget to turn on interpolation

swift falcon
#
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

[RequireComponent(typeof(PlayerController))]
public class Player : MonoBehaviour
{

    PlayerController _playerController;
    Vector3 normalized;


    void Start()
    {
        _playerController = GetComponent<PlayerController>();

    }

    void Update()
    {
        Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
        normalized = input.normalized;

        if(normalized.magnitude > 0.05f)
            _playerController.LookAt(normalized);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            _playerController.Jump();
        }
        _playerController.Move(normalized);
       


    }

   
}
swift falcon
swift falcon
#
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{
     Rigidbody _rb;
    public float Speed = 8f;
    public float force = 10f;
    public float RotationSmoothValue = .1f;
    private void Start()
    {
        _rb = GetComponent<Rigidbody>();
    }

    public void Move(Vector3 position)
    {

        _rb.MovePosition(_rb.position + position * Time.deltaTime * Speed);

    }

    public void LookAt(Vector3 input)
    {
        float angle = Mathf.Atan2(input.x, input.z) * Mathf.Rad2Deg;
        float lerpedAngle = Mathf.LerpAngle(transform.rotation.eulerAngles.y, angle, RotationSmoothValue);
        transform.rotation = Quaternion.Euler(0, lerpedAngle, 0);

    }

    public void Jump()
    {
        _rb.AddForce(Vector3.up * force * Time.deltaTime,ForceMode.Impulse);
    }
}

leaden ice
#

Wait what

#

There's so much going on here

swift falcon
#

two script connected each other basically

cosmic rain
swift falcon
#

first one handles the input, second one handles the movement

leaden ice
#

Ok you're doing a lot of things wrong here

#

All Rigidbody movement needs to be in FixedUpdate

#

Interpolation needs to be on

#

And the camera should move in Late update

swift falcon
#

So should I call the methods in FixedUpdate?

#

or directly write in there?

leaden ice
#

And deltaTime does not belong in AddForce calls

swift falcon
cosmic rain
#

Oh, it's PlayerController, not a CharacterController(CC)๐Ÿ˜…

swift falcon
#

so let me write movement functions in FixedUpdate and ill see if it's fix the problem

cosmic rain
#

Setting transform.rotation would break interpolation too, so you'll need to rewrite that.

gleaming brook
safe dirge
#

Has anyone encountered an issue with [SerializedField] where you go to change it and unity does something for like 2minutes and sticks like 5gb of stuff into memory before letting you edit it? and when you deslect the game object it will go for another 2minutes and remove all that memory

leaden ice
#

What was the change you made

safe dirge
#

It's a fairly simple script, it's on a single object all I did was add an an additional field for a float, and there's only like 10 others on the script, all either floats or Vector2s

#

Think I found the issue, it had something to do with other private variables I had on the script, they weren't serialized, but when I added [NonSerialized] to them the issue stopped. so goddamn weird, still wish I knew why

leaden ice
safe dirge
#

yup

leaden ice
#

When the inspector is in debug mode it serializes private variables

#

So that would explain things

safe dirge
#

thanks! I'll keep that in mind

heady iris
#

I've encountered that before

#

It was particularly insidious with the new input system. I wound up with an input action that wasn't null, but was also completely bogus

icy schooner
#

I'm trying to use the OntriggerEnter in my code but it only triggers when the Character controller is inside something but not when the box collider which is trigger enabled collides with something.

knotty sun
tawny elkBOT
icy schooner
# knotty sun show inspectors of both objects and your !code

Both colliders are on same object.

 private void OnTriggerEnter(Collider other)
 {
     Debug.Log("Trigger enter " + other.name);
     if (other.TryGetComponent(out IInteractable interactable))
     {
         Debug.Log("IInteractable");
         if (lastHoveredObject != interactable)
         {
             // Call Unhover on the last hovered object if it's different from the current
             lastHoveredObject?.ExitHover();
             lastHoveredObject = interactable;
         }

         interactable.Hover();
         Debug.Log("Hover");
         //actionText.text = interactable.InteractionPrompt;


         if(input.Player.Interact.WasPerformedThisFrame())
         {
             Debug.Log("Interact Player");
             interactable.Interact(this);

         }

     }
 }

 private void OnTriggerExit(Collider other)
 {
     if (lastHoveredObject != null)
     {
         Debug.Log("lasthovered exit hover " + lastHoveredObject);
         lastHoveredObject.ExitHover();
         lastHoveredObject = null;
     }
 }
knotty sun
#

' when the box collider which is trigger enabled collides with something.'
Then what is the 'something' in this sentence?

icy schooner
#

Anything with a script that has the IInteractable interface

knotty sun
#

then that is the other of the 2 objects I'd like to see the inspector of

rigid island
#

use physic queries and you exclude the player layer from it

#

using triggers for interactions is mid

icy schooner
icy schooner
rigid island
#

Raycast, Spherecat, Boxcast etc

icy schooner
#

I have used raycast but I wanted to have a less accurate on so I went for collider

heady iris
rigid island
icy schooner
heady iris
#
  • Character <-- CharacterController, third person controller, input component
    • Visual <-- Animator
    • Interaction Trigger <-- just a trigger collider and a comopnent that looks for triggers
#

Parenting the visual to the character makes it easy to adjust the visual's position (or to animate it, even)

icy schooner
rigid island
#

yeah just easier to deal with once you get used to how they work

#

no rigidbodies invovled etc

icy schooner
#

it seems like it will be better so thank you

heady iris
#

Using a physics query is nice beacuse you can do it whenever you want

#

instead of having to wait for a collision or trigger in a physics update

lunar kestrel
#

Is there a way to have multiple scenes opened at the time by default?
When I work with stuff I need to switch between them and each time I need to drag player scene again,
is there way to have them opened from some like scene set or something?

serene stag
arctic seal
heady iris
#

you have to manually open multiple scenes at once in unity

#

What you can do is just unload one scene and load another one

versed pagoda
#

Does anyone know a good way of handling moving platforms on a 2D platformer game? I'm currently using OnCollisionEnter2D/OnCollisionExit2D to parent my player to the platform, it works, however when my player is on a platform that is moving down and he jumps, he starts to bounce

#

Also by using this parent method, whenever i get from the left platform to the right platform by walking my player is no longer parented to any platform at all and just falls

gray mural
#

OnCollisionEnter2D and OnCollisionExit2D are usually the best way to do it. I suppose, you might want to temporary avoid the collision with the platform using the Physics.IgnoreCollision method

versed pagoda
#

Whenever he bounces off like in the video the OnCollisionEnter2D doesn't gets called as it should

knotty sun
#

should that not be OnColliderExit2D ?

gray mural
versed pagoda
knotty sun
#

well when you leave a collider that is what is called

versed pagoda
#

When my platform is moving down and i jump, whenever my player hits the platform again and cause it to bounce like in the video i should be getting a OnCollisionEnter2D call

#

I'm not

gray mural
#

Does your player have any additional behavior, which might cause the bounce? If the player is parented corretly, the colliders are moved simultaniously, the way neither enter nor exit methods are called

knotty sun
#

but are you getting an OnColliderExit2D ?

gray mural
#

You should be getting both methods if the colliders are set up correctly

knotty sun
#

then he has not left the collider, so no OnColliderEnter2D

versed pagoda
#

He left the collider when he jumped

gray mural
#

Please, show both colliders in a screenshot

knotty sun
#

you do not know that, you are assuming

versed pagoda
gray mural
knotty sun
#

ok, tell me if he left the collider why no Exit event ?

versed pagoda
#

The colliders

versed pagoda
gray mural
#

This way, anything colliding with the child's Collider will also call the collision method for the parent

#

So you either manage this by unparenting the player from the platform, or parenting and then unparenting it once the player hits your ground, which means there is no collision with the platform anymore

versed pagoda
#

I can't unparent only when he hits the ground, this way he wouldn't be able to jump when standing on the platforms, given that the parent transformations affects the childs and my platform is going down

gray mural
#

What is that supposed to mean?

#

Why cannot you unparent it?

versed pagoda
#

You said that i should only unparent the player after he hits the ground

gray mural
#

Right

#

Or the 1st variant

versed pagoda
#

That makes no sense, if i let my player parented on the platform while he is jumping in the air he would get the velocity of the platform as it's her parent, and due to that he wouldn't be able to jump

gray mural
#

Can you jump while being in a lift?

lament island
#

Hello, I've been working on a VR spaceflight game for the past 7 months and have made considerable progress but I'm about to try and tackle the biggest bear in the whole project. AI navigation. This scares me for a number of reasons because 3D navigation is a very complicated field with a lot of possible solutions. I've been looking into RVO thus far and it seems quite complicated. I considered also taking an even simpler approach by using something like boids and using the obstacles as static boids. These are all plausible approaches. I've also considered doing A* in an SVO but I'm not sure how to use the rigidbody physics to follow the path. Where would you recommend me going in terms of research? I'm rather overwhelmed trying to find a reasonable solution and I just need to know where to start more than anything

exotic tartan
#

Hello, I am working on a simulation where each room in a building needs to be detailed and that comes with some lag. I plan to use triggers to load and unload objects in each room. It would likely take around 100 triggers and many of them would overlap with one or two others. Would this cause any significant issues or lag?

late lion
leaden ice
#

try it and see

lament island
#

Octree is probably overkill thinking about it

heady iris
#

If it's mostly empty space, boids sounds plenty good

#

or some really basic obstacle avoidance where you just steer away from stuff in your face

#

with complex spaces, your life gets a lot harder :p

lament island
#

I've seen the Warframe talk, that's why I originally started on A* in an SVO but the optimization would be a nightmare for a small team

#

I've only had a few years in C# but I've successfully implemented an SVO already but my main worry is dealing with velocity for the paths

#

The greedy method based on voxel size and other optimizations are cool AF tho ngl

exotic tartan
haughty ember
#

For inventory systems with a hotbar (think an inventory basically the same as minecraft's) do people usually use 2 lists, one for hotbar and one for an inventory? Or do they use one list that holds both, maybe with a slot data structure to mark whether a slot is a hotbar slot or an inventory slot? I know inventory systems in general are difficult, so I'm just curious to see what people think before I start implementing one system and then it turns out the other may have been better

lament island
haughty ember
# lament island I have not really implemented an inventory system so take my response with a gra...

Yeah I was thinking this too, I did start working on it with the 2 separate lists but it got kinda clunky pretty quick so I figured maybe not the best idea. Specifically switching items between the 2 lists seemed to lead to a lot of if statements when moving stuff around (inventory to hotbar, hotbar to inventory, hotbar to hotbar, etc.). Just not sure if the struct approach is gonna have some issues too but I guess I'll just have to try it

exotic tartan
haughty ember
lunar kestrel
#

and switching scenes in editor removes the second one when I'm coming back

snow yarrow
#

what are the format options? i searched for a documentation but did not find any

i would like to display a timer/countdown for a project for university and somehow i cant display time going down from 01:00 to 00:59

provided screenshots are how it looks right now
format type right now is 0:00

simple egret
simple egret
#

Yes modulo operation which gets the remainder of a division

#

65 % 60 = 5

#

65 / 60 = 1
Which gives 1 minute and 5 seconds

heady iris
#

nitpick time

#

it's actually the remainder operator!

#

it's equivalent to the modulo operator for positive numbers, but not for negative numbers

#

-1 mod 5 is 4
-1 rem 5 is -1

#

(this is annoying when you're trying to, say, wrap around a list)

#
index -= 1; // suppose index was 0, so now it's -1
index %= list.Count; // wrong! index is still -1
#

it'll work just fine here, though!

snow yarrow
#

so like this basically in the first steps, now i only need to fix the time being shown as 1:60 for the split sec

simple egret
#

I'd convert the values to integers if I were you, before doing all of these operations

#

That's probably why you get the incorrect "1:60" for a split second

snow yarrow
simple egret
#

Good question, this channel is usually for the C# version

#

Search the documentation

snow yarrow
#

oh my bad, but thanks for your help you gave me great help tho

simple egret
#

Search for any node that can round a value down (works properly in your case as long as your number isn't negative), cast it to an integer, or truncate the number

snow yarrow
opaque forge
grave thorn
#

Hi, so I instantiate this bullet in the "Gun" script when I fire the gun. there is a float variable called speed on the 'Bullet' script, which sits on the bullet, how do I modify that variable, right after instantiating the bullet.

This is the instanition code:

Instantiate(bulletPrefab, firePoint.transform.position, firePoint.transform.rotation);
leaden ice
#

Change it there

grave thorn
#

oo nice could u link a example?

leaden ice
#

Scroll down and look at the examples

grave thorn
#

Oh great i didnt know this.. IT WORKS

#

omg tysm ๐Ÿ™

#

i was at this for far too long

shell scarab
#

At runtime is changing a prefab reference undefined behavior (as in adding a component to the prefab)? Also I assume that changing a prefab at runtime will change it for everything that references it?

lean sail
shell scarab
lean sail
#

It's not really something you should be doing anyways

shell scarab
#

ok. Is there a way to sort of create a prefab at runtime? Like a game object reference that's not instantiated?

latent latch
#

just make a gameobject?

shell scarab
#

that's what I'm doing right now but I have to keep it inactive and every time it's instantiated we need to remember to activate it so its a bit annoying. A "virtual" object would be more convenient.

latent latch
#

ah, right you want it living off the scene like a normal prefab

#

not too sure exactly. I know you can do stuff with asset bundles, but the stuff that is loaded into mem is already precreated

#

Usually you want your prefabs to have some assignment methods too which is where I do my enable logic

remote shard
#

this code gives me this error BUT the debug code shows the right ID? (slightly cut in the screenshot)

Why is that?

plucky inlet
shell scarab
plucky inlet
#

GameObject is just a unity thing. If you create a new object of type gameobejct, Unity knows to create a hierarchy object But if you create a new instance of a class for example, it can live at runtime without being in hierarchy

leaden ice
remote shard
shell scarab
#

so Instead when the extra behaviors are added, they're added to the object that's already instantiated that is then instantiated again to spawn the objects that will be used. This may be pointless because maybe unity just calls add component when it instantiates the object, no idea.

remote shard
leaden ice
plucky inlet
remote shard
leaden ice
#

sounds loike what you want is to just save the ID and get the instance of the chest with that ID that's in the current scene

#

with something like an ID component like that, you should probably have a way to look up an object in the scene by the ID

shell scarab
remote shard
leaden ice
#

then use that in your other code to find the current instance with that id

remote shard
leaden ice
#

I mean isn't that pretty much the whole point of the dictionary

#

to look things up by ID

plucky inlet
leaden ice
#

just use the dictionary you already have...

latent latch
remote shard
#

oh, i thought you meant in the scene'

leaden ice
#

since OnDestroy removes them

plucky inlet
remote shard
shell scarab
# latent latch Can probably just make a factory type class that you feed component types and it...

thats sorta what I have. The whole thing is about adding upgrades that have special behaviors to the projectiles fired from guns. So what I have now is an SO with a serialized read-only property that is assigned a projectile prefab in the inspector (and other weapon stats. Also it's not actually read-only, it's {get; privateset;}). Upgrades are not tied to the weapon, so whenever the weapon changes a new projectile is loaded in the "weapon container" class from that SO into the weapon container via instantiation and then adds all the behaviours in the "active behavior" list to that object. When a new behaviour is added it does a similar thing.

leaden ice
#

As i said, you need to add a function to UniqueId to look objects up.
And you need to use that function in the other script

remote shard
leaden ice
#

That is one of the scripts, yes.

#

I said you need to change both

remote shard
#

yeah, so uniqueids and that one

plucky inlet
shell scarab
#

im not exactly following your logic twentacle

forest vigil
#

Why is my npcPos in the right position but my rotation is not? I tried printing both npcRot and gameCamera.transform.rotation and it gives two different values

 public Vector3 npcPos;
 public Quaternion npcRot;
            gameCamera.transform.position = npcPos;
            gameCamera.transform.rotation = npcRot;
            Debug.Log(npcRot + "" + gameCamera.transform.rotation);
shell scarab
#

also, any given rotation has two possible quaternion representations

leaden ice
forest vigil
forest vigil
leaden ice
#

I really doubt it has anythong to do with that

shell scarab
#

transform.rotation returns a quaternion

leaden ice
forest vigil
#

I'll try to provide context hold on

leaden ice
#

Show what this setup is

shell scarab
#

ah then probably nothing to do with that like praetor blue said

plucky inlet
forest vigil
#

To keep things simple this isn't the full code but it should include everything needed. I attached the values.

public Vector3 camera2Pos; // CAMERA2: The position where our second cutscene shot takes place. This will serve as the PLAYER camera position.
public Quaternion camera2Rot; // CAMERA2: The position where our second cutscene shot takes place. Serves as PLAYER camera position.
public Vector3 npcPos;
public Quaternion npcRot;
    public void Update()
    {
        Debug.Log(shotTimer);
        Application.targetFrameRate = 60; // Avoiding any cracking for stronger PCs
        if (mainCanvas.transform.position.x < menuEnd && shotTimer < 75)
        {
            StopCoroutine(MenuTimer());
            StartCoroutine(Camera1());
        }
        if (shotTimer > 79 && 130 > shotTimer) // 80 is the magic number. 99 is to save the amount of variables used.
        {
            gameCamera.transform.position = camera2Pos;
            gameCamera.transform.rotation = camera2Rot;
            shotTimer += 1;
        }
        if (shotTimer > 129 && shotTimer < 220) //  Shot 3
        {
            gameCamera.transform.position = npcPos;
            gameCamera.transform.rotation = npcRot;
            Debug.Log(npcRot + "" + gameCamera.transform.rotation);
            shotTimer += 1;
        }
latent latch
#

Ya really should take a look into unity's timeline tool if you're doing cinematic work

forest vigil
#

camera2Rot and transform rotation don't perfectly work either, by the way

leaden ice
#

this feels massively overcomplicated. Have you looked into Timeline?

remote shard
forest vigil
#

Yeah I found out about it 30 minutes ago but i need to fix rotations before I can get to optimizing

leaden ice
#

this... is not necessary at all

#

and already handled by the other code in the script

#

And this doesn't solve your problem

forest vigil
#

And for context this is what the Debug for Debug.Log(camera2Rot + "" + gameCamera.transform.rotation); looks like

remote shard
leaden ice
dense sparrow
#

Does anyone know how to find a point on the edge of a Bounds object?

remote shard
#

but isn't that not what I already do here?

#

like, didn't you say the problem is that it's not finding the "ChestInventory" script, because the instance was removed when i unloaded and reloaded the scene?

leaden ice
#

chestDictionary

#

what is that

#

that's a bad idea basically

#

you shouldn't be holding a reference to the actual chest object in your save data

#

you should just have the ID

remote shard
leaden ice
#

Yeah I know

forest vigil
leaden ice
#

that's a terrible idea

leaden ice
#

ok

#

you're looking at the wrong thing here entirely

#

Look at your error

#

Your ChestInventory reference itself was wrong

#

You need to show the full stack trace of this error

remote shard
leaden ice
#

you've got some reference to a ChestInventory instance

#

that reference is referring to a destroyed object

remote shard
remote shard
#

so it's just not finding the object in the scene

remote shard
#

which is why i thought I had to find the bojects in the scene with IDs to add them back

leaden ice
# remote shard

Looks like you're subscribing to OnLoadGame but you never unsubscribe

leaden ice
remote shard
leaden ice
#

The counterpart to Awake would be OnDestroy

remote shard
#

oh sorry yeah, was looking at wrong code

remote shard
#

Second quick problem though, when i join the game now, no errors, but the chest inventory doesn't load until i manually do it in update

Note that this code runs after the default time and after the uniqueid (which runs on default)

#

it seems like the TryLoadData(); doesn't run at the right time

leaden ice
#

time to pull out Debug.Log

#

see what's happening and when

remote shard
#

i've been using print(); to debug, is there any difference (other than the namespace it's using)

plucky inlet
remote shard
remote shard
plucky inlet
# remote shard

You are calling the same thing twice in your start, not sure wheres the error there

#

TryLoadData() on both lines

remote shard
plucky inlet
#

Where is LoadInventory?

plucky inlet
#

are you sure its subscribed and the object is active?

remote shard
#

oh

#

i just found the reason

#

that second script is on another scene that is loaded additively

#

on start

#

I guess, can I load a scene on awake?

plucky inlet
#

You can load a scene whenever you like from script

remote shard
#

fixed

#

omg lol. 1h20min of debugging for 1 line of code and 1 word change HAHAHHAHAH. coding lifestyle is real

#

thanks bro

#

appreciate it A LOT

plucky inlet
#

Does not sound like a save way of loading your stuff tho, if you have general values/save games etc and when loaded subscribed events are sitting in another scene

remote shard
#

I know, but if it works, that's all I care about. I'll fix my code when i get player complaints that the game crashes and runs at 5fps ๐Ÿ˜‚๐Ÿคฃ

plucky inlet
#

So thats how the devs behind early access and big first day patches think to rely on the user to bugfix their code ๐Ÿ˜„ best of luck to you with that ๐Ÿ˜‰

true crater
#

Is it possible to sample the actual depth from _MainLightShadowmapTexture?

#

(this is in URP)

mortal flame
#

how many if statements is too much?

cosmic rain
twilit ruin
#

I was looking to get some help with minor gameplay mechanics and gameplay tweaks like, sliding, air control, my velocity while jumping, and things like that. If anyone would be either available to do a live chat with me or just give some help in general that would be greatly appreciated
this is my code: https://pastecode.io/s/v4cz0iu4

lean sail
mortal flame
#

ohh okay thanks

lean sail
twilit ruin
swift falcon
#

Write your code in a way that makes sense to you. Later on, efficient ways of writing code will make more sense. There's many ways to write the same thing, dw about this while you're learning.

#

@mortal flame

mortal flame
#

gotcha

lean sail
marble osprey
#

My playerAttack dont call the axe attack ienumerator

public class PlayerAttack : MonoBehaviour
{
    [SerializeField] private PlayerAxe axe;
    void Start()
    {
        
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Debug.Log("HYAH");
            axe.Attack();
        }
    }
}

so I got this player attack placeholder script that calls the axe attack

public class WeaponFramework : MonoBehaviour
{
    protected float damage;
    protected float attackWait;
    protected float attackCooldown;
    public bool canAttack;
    protected LayerMask[] targets;

    public virtual IEnumerator Attack()
    {
        //to copy and paste mostly
        if(!canAttack)
        {
            yield return null;
        }

        yield return new WaitForSeconds(attackWait);
        canAttack = false;

        //attack

        yield return new WaitForSeconds(attackCooldown);
        canAttack = true;

        yield return null;
    }
}

this was the weapon framework
and the axe script

public class PlayerAxe : WeaponFramework
{
    ...

    public override IEnumerator Attack()
    {
        Debug.Log("axe attack");
        if (!canAttack)
        {
            yield return null;
        }

        yield return new WaitForSeconds(attackWait);
        canAttack = false;

        //AOE
        Collider[] hit = Physics.OverlapBox(_damageZoneOrigin, _damageZoneScale / 2);
        foreach (Collider elements in hit)
        {
            foreach(LayerMask layer in targets)
            {
                if(layer == layer << elements.gameObject.layer)
                {
                    elements.gameObject.TryGetComponent<Health>(out Health target);
                    target?.SetHealth(target.GetHealth() - damage);
                }
            }
        }

        yield return new WaitForSeconds(attackCooldown);
        canAttack = true;

        yield return null;
    }
marble osprey
#

yea srr

lean sail
marble osprey
#

yea I fixed that

#

that was really stupid of me

coral mesa
#

Hi there! Can someone help me out with this code?
https://github.com/CatchFireDev/CARTBOARD/blob/7ac821103b9e5367b9b65bb54c50867130d51b3e/PickUpObject.cs
I've written this to pick up and throw objects. But I want to make it so that only when i 'TAP' the E button the object is being picked up (inside the transform hand), and when I am tapping the e button once again (1time), it just drops like normal, but if I HOLD the E button the throw starts charging and when I release it then it gets THROWN.

GitHub

Contribute to CatchFireDev/CARTBOARD development by creating an account on GitHub.

cosmic rain
simple egret
#

On key down: start timer.
On key up: stop timer. if the timer is lower than some threshold, drop the item. Else, calculate a force based on the value of the timer and throw towards it. Reset timer to 0.

coral mesa
simple egret
#

That's it, just the threshold exposed. You also need another float in which you add Time.deltaTime in Update for as long as the key is down

#

(that's your timer variable)

coral mesa
#

I don't get it haha I tought I got it ๐Ÿ˜„ Could you write me the line of code just to compare? And tell me where exactly i need to put that? I'm kinda confused ๐Ÿ˜„

simple egret
#

In Update:

if (key down)
    timer += Time.deltaTime;

if (key up)
{
    if (timer < threshold)
        // drop
    else
        // throw

    timer = 0
}
#

Pseudo code, real implementation is an exercise left to you

coral mesa
#

Aah yes I think I see it now! Big t

#

thanks!

#

for the help

swift falcon
#

Trouble wiht code

#

anyone can assist ๐Ÿ™‹ ?

rough crescent
swift falcon
#

nvm too late

#

i am busy

#

kinda

rough crescent
#

workign on procedural flower gen, my gizmos aren't clearing on frame end? is this normal behaviour ?

somber nacelle
#

where are you drawing the gizmos

rough crescent
#

forgot to post that part xd

#

nvm i figured it out

#

first time doing c# for some time shit works differently from what i'm used to

lethal lagoon
#

can anyone explain why my bullet doesn't speed up when i change the bulletSpeed variable

somber nacelle
#

where do you change it? because in the code you've shown the only place it changes is Start which happens before any Update calls so it won't "speed up" so much as "start at that speed and remain at that speed"

lethal lagoon
#

I change it in this script

somber nacelle
#

and you are certain that you are changing this on the instance in the scene and not the prefab?

lethal lagoon
#

it only changes the prefab but no the one in the scene

somber nacelle
#

so then you need to modify the objects in the scene not the prefab

spring creek
#

Then it will not affect an instance that has already been instantiated

lethal lagoon
#

how do I do that

tame shoal
#

hey, i'm getting these two errors on line 306, just can't figure out what's wrong there shouldn't be any reason for the error right?

spring creek
somber nacelle
gray mural
tame shoal
#

it should be all zero

gray mural
tame shoal
#

yes

gray mural
#

The pathInfo.carPrefab?

tame shoal
#

its the root gameobject, it shouldn't be moved from 0, 0, 0 even at runtime

#

yeah

#

and when i tried setting the prefabs position to something different it also showed the error, the same when the commented out part of the instantiate call was there

spring creek
#

If it is in the scene, it is not a prefab

tame shoal
#

the screenshot is from the prefab

gray mural
#

This is an instance

#

Click on your prefab in the assets

#

And then show the screenshot

tame shoal
somber nacelle
spring creek
#

Looks like a prefab to me

#

They have it in the prefab view

gray mural
tame shoal
#

shouldn't that be the same?

gray mural
#

I forgot that the prefab is opened without the "prefab asset" message above

gray mural
tame shoal
#

like this?

gray mural
#

Yes

tame shoal
somber nacelle
#

can you show the full stack trace for the error

tame shoal
#

the error also started by itself, i was changing quality settings, there hasn't been anything changed on the prefab or the script and it was working before

gray mural
#

Use multiline code instead.

tame shoal
#
UnityEngine.Object:Instantiate<UnityEngine.GameObject> (UnityEngine.GameObject)
PathManager:SpawnCars () (at Assets/Scripts/PathManager.cs:307)
LevelManager:Awake () (at Assets/Scripts/LevelManager.cs:26)```
#

yeah sorry

gray mural
#

I feel like this is a bug

gray mural
tame shoal
#

i tried restarting it, reimporting all and invalidating the GI cache

somber nacelle
tame shoal
gray mural
rigid island
gray mural
rigid island
#

yeah but why was that it before that lol

gray mural
rigid island
#

is the error showing up when those are commented out?

tame shoal
#

just tried:
Instantiate(pathInfo.carPrefab, Vector2.zero, quaternion.identity) - same error
Instantiate(pathInfo.carPrefab, Vector3.zero, quaternion.identity) - same error
Instantiate(pathInfo.carPrefab, Vector3.zero, Quaternion.identity) -same error
Instantiate(pathInfo.carPrefab) - same error

somber nacelle
#

reset the transform component and see what happens

spring creek
#

I feel like the code isn't compiling between changes then. The first two should have given you new errors

#

Have you tried hitting ctrl+r in unity?

tame shoal
somber nacelle
#

nah, Unity.Mathematics.quaternion has an implicity cast to UnityEngine.Quaternion, same with Vector2 to Vector3

gray mural
spring creek
#

Gotcha

gray mural
somber nacelle
spring creek
#

And I guess the debug showing up proves it is compiling. Missed that part

tame shoal
tame shoal
somber nacelle
#

verify that by disabling it

tame shoal
#

still the same

somber nacelle
#

in that case i'm out of ideas. try creating a different prefab with the same components on it and see what happens ๐Ÿคทโ€โ™‚๏ธ

glacial halo
#

!ide

tawny elkBOT
tame shoal
#

well now i got somewhere

#

disabling the splineanimate didn't do nothing, but changing the reference to the splinecontainer to "None" gets rid of the error for some reason

somber nacelle
#

is it referring to a spline container on a separate prefab?

tame shoal
#

no the containter is on the parent

#

the reason for this is i think because when the splineanimate was on the same gameobject as the container, by moving itself it also moved the containter which works in local space, not world space. Basically it would move all over the place

civic igloo
#

What time is Time.deltaTime exactly measuring? I mean like is it between Updates, LateUpdates, or between Update and LateUpdate? Is it recalculated every time its called?

somber nacelle
gray mural
tame shoal
#

well i guess i fixed it, i removed the reference to the spline container, and it is now set at runtime. Don't really know why it was set to play on awake, because the spline in the container in the prefab was only a placeholder, and it was changed after spawning the car (wrote it a few weeks ago lol). But i started up a version of the project from a few hours ago, and it worked there๐Ÿคทโ€โ™‚๏ธ

somber nacelle
#

check what changes you have made in whatever version control you are using. (i am going to give you the benefit of the doubt and assume you are using version control and not just copy/pasting your project to keep backups of it)

tame shoal
#

lol don't worry

#

all the changes are about URP because the simple project was getting like 15 fps on my not so bad phone. There were also some package updates but i'm 99% sure it didn't throw the error while i was doing the optimizations. What pisses me off the most is that i was almost ready to make the commit when the error started lol.

cursive halo
#

i'm having some trouble because Update() isn't being called from this monobehaviour.
the object is enabled, the behaviour is enabled, and i am certain it isn't being called because i've tried sending things to console in Update() and that hasn't worked either. no other object currently has an update function afaik
any ideas would be much appreciated

spring creek
#

Console writeline should not be used in unity

knotty sun
#

hmm, Console.Writeline does not work in Unity

spring creek
#

Debug.Log

cursive halo
#

ok i'll try that

#

ok so it is being called ig
now i just need to sort out the rest, thank you :)

#

ah i figured it out, i'm multiplying by the health but the health isn't a fraction so it is just scaling the image up to like 100 times rather than scaling it down
i didn't notice because of the mask :p

somber nacelle
#

for a healthbar, instead of modifying the sizeDelta, i'd recommend using an Image component with the Filled Image type. then you can just modify its fill amount. it will also look a lot nicer that way

heady iris
#

You can also set its anchor points, if you can't do a filled image for some reason

#

maybe you want to use a 9-sliced sprite instead

#

in that case you just adjust the max anchor between [1,1] (full) and [0,1] (empty)

latent latch
#

Let's say I want to make some utility methods like ClosestTransformSqrMagnitude & ClosestTransformDistance, but I want to feed these methods with different list/array types like Colliders. Would it be suggested just to make duplicate methods but for these different types? Not too sure how I can accomplish this with something like generics otherwise.

knotty sun
fervent furnace
latent latch
#

I guess also a follow up to the questions is casting these data containers to another type and the difference in performance

#

considering these operations are in update loops and constantly being evaluated

#

as in list to array and vice versa

#

I'd expect I should just make two methods in that case?

knotty sun
#

list to array is not a cast it's a copy so better to have overrides for both array and List

chilly surge
#

Could also do IEnumerable<T>.

knotty sun
#

good point, better

chilly surge
#

Well, unless you need indexed access.

somber nacelle
#

use IList in that case

latent latch
#
public static Transform FindClosestTransformSqr<T>(Vector3 referencePoint, IEnumerable<T> components) where T : Component
{
    Transform closestTransform = null;
    float closestDistanceSqr = Mathf.Infinity;

    foreach (T component in components)
    {
        Transform targetTransform = component.transform; 
        Vector3 displacement = targetTransform.position - referencePoint;
        float distanceSqr = displacement.sqrMagnitude;

        if (distanceSqr < closestDistanceSqr)
        {
            closestDistanceSqr = distanceSqr;
            closestTransform = targetTransform;
        }
    }

    return closestTransform;
}

I guess something like that? Pretty odd how I can't just use Transform as the constraint

knotty sun
#

because then everything you passed would have to inherit from Transform. you are ony using a property

latent latch
#

Ah, yeah that's true

knotty sun
#

remember to check for null when the method returns

#

you might also consider an out parameter to contain the distance found

gaunt nexus
#

guys im making a dash attack but i don't know how
i want to dash through enemies and hit them on collision but to be able to dash through enemies i disabled the layermatrix between them but how am i gonna damage them now

somber nacelle
#

instead of modifying the layer matrix, you could instead change your collider to a trigger so you still at least get OnTrigger messages

knotty sun
leaden ice
gaunt nexus
somber nacelle
#

well that depends entirely on your setup

#

just go with the physics query option

gaunt nexus
#

uhhh what is that?

somber nacelle
gaunt nexus
#

so what's the solution then

somber nacelle
gaunt nexus
#

what is CapsuleCast

spring creek
#

Did you google the docs for it?

leaden ice
#

like a raycast but capsule shaped

gaunt nexus
#

i never used raycast before cuz it sounds scary

#

and complex

#

but is it?

leaden ice
#

you will need to learn raycast

#

if you want to make games

#

it's really not that bad

#

Imagine shining a laser pointer into your scene from a specified place and seeing what it hits

#

that's all it is

spring creek
# gaunt nexus but is it?

There are a ton of good guides on it. There are some complexities, but that is par for the course in game dev. Compared to most things you will have to deal with, it is dead simple

gaunt nexus
#

wait i have an idea

#

whta if i keep my disable layer matrix but i test if the distance between the enemy and the player is very small then the enemy takes damage

somber nacelle
#

you would need to already have a reference to the enemy to do that. the cast will be better that way you don't need a reference to every single enemy in the level to check the distance, you just use the cast to determine whether the player will hit an enemy

pure ore
#

Can someone help me here? I'm trying to clamp my x and y axis but its not working as expected

    public Quaternion ClampXAxis(Quaternion quaternion, float minimum, float maximum)
    {
        quaternion.x /= quaternion.w;
        quaternion.y /= quaternion.w;
        quaternion.z /= quaternion.w;
        quaternion.w = 1f;
        float value = Mathf.Atan(quaternion.x);
        value = Mathf.Clamp(value, minimum, maximum);
        quaternion.x = 115.5916f * Mathf.Tan(Mathf.PI / 360f * value);
        return quaternion;
    }

    public Quaternion ClampYAxis(Quaternion quaternion, float minimum, float maximum)
    {
        quaternion.x /= quaternion.w;
        quaternion.y /= quaternion.w;
        quaternion.z /= quaternion.w;
        quaternion.w = 1f;
        float value = Mathf.Atan(quaternion.y);
        value = Mathf.Clamp(value, minimum, maximum);
        quaternion.y = 115.5916f * Mathf.Tan(Mathf.PI / 360f * value);
        return quaternion;
    }
}
charred imp
#

is anyone good with using the Destructible 2D plugin?

latent latch
#

must have missed the big large text that says don't modify quaternions directly

pure ore
#

wdym

latent latch
pure ore
#

What is another way of clamping then?

leaden solstice
latent latch
#

angleaxis probably the most defined way of doing quaternion rotations so that's a good starting point

pure ore
#

I forgot it but I'm tyring to remember it

pure ore
knotty sun
pure ore
#

How do I do that?

knotty sun
pure ore
#

what does that even mean

knotty sun
#

it means it went bang, very frequently