#archived-code-general

1 messages · Page 176 of 1

rigid island
#

oh you mean create the actual ScriptableObject by code?

#

confused what you meant exactly lol

scarlet kindle
#

yeah i need to create them, then add to the Deck's List<Card> which will actually be a Stack, gotta change that

#

so i think this shouldu work

#

so would it be like Card.CreateInstance("Attack")

#

?

leaden solstice
#

Don’t use SO to represent mutable data

scarlet kindle
#

why

rigid island
scarlet kindle
#

yeah i thought about that, but if i'm not showing them in the game yet, why would i instantiate the GameObjects?

rigid island
#

typically thats why my Card is the Monobehvaior and CardSO is my scriptable object

rigid island
scarlet kindle
#

Oh yes, I do! But I wasn't going to create the gameObjects until they are in the Hand, on the screen

rigid island
#

thats why makes SO great you can just make a slot for this Data and swap them out

rigid island
scarlet kindle
#

I could see that use case you just explained, because if the cards have temporary in-game modifiers, or upgrades... things that would be pertinent to a player's custome xperience, then instantiating all the cards in a hidden way might be better

rigid island
scarlet kindle
#

i was wondering if it might be more resource intensive to pre-instantiate all the cards though? purely from a resource standpoint I'd think that only creating GOs in-handmight be more efficient... BUT at the cost of not being able to do what you're mentioning above.

spark stirrup
#

How should I go about block face culling

sage latch
#

Or just call it Card

rigid island
#

thats what they have already iirc

sage latch
#

Ah

rigid island
#

they're just confusing which one to modify i think

scarlet kindle
#

or is that different than a GO

sage latch
#

Yeah can be

rigid island
leaden solstice
#

Just POCO should be enough

rigid island
rigid island
#

thats your actual Instance that holds the SO data / reads it

leaden solstice
#

It doesn’t have to be MB or SO

rigid island
#

yea its easier to work with MBs tho

scarlet kindle
#

what's MB?

rigid island
#

MonoBehaviour

scarlet kindle
#

ah gotcha

rigid island
#

it can sit on a gameobject when MB

sage latch
#

I think you ideally want 3 classes:

  • A data ScriptableObject
  • A normal class that holds a reference to data and extra modifiers
  • A display MonoBehaviour that holds a reference to an object of the class and displays it
spark stirrup
scarlet kindle
#

is GO & MB synonymous in most contexts?

sage latch
leaden solstice
#

I’d generally call second one “Model” and third one “View”

rigid island
rigid island
scarlet kindle
#

I may have to do that as well, I have multiple scenes for my project already

#

Is that the only way to save a deck between different scenes & canvases?

sage latch
#

Then the display objects dont carry any data and can be destroyed/initiated however you want

rigid island
#

yes

#

but depends on your usecase

sage latch
#

You definitely want to implement object pooling though

scarlet kindle
rigid island
sage latch
jolly sorrel
#

I'm switching to unity any tips to make a tower defense like a yt tut

rigid island
#

Ah UI is such a pain in the ass to make a game with

rigid island
#

also don't crosspost

spark stirrup
rigid island
#

been coding a while

#

never heard of this

spark stirrup
rigid island
spark stirrup
#

I originally made up the blocks of 6 planes, which I disabled their renderers when they weren't needed, but now my blocks are one solid model

leaden solstice
#

That happens automatically already

rigid island
#

wouldn't be easier to cull separate planes then one whole giant block?

spark stirrup
spark stirrup
rigid island
#

maybe a shader could help culling certain areas?

#

idk if it would help perfm

leaden solstice
spark stirrup
#

also where is the profiler? I haven't been able to find it

sage latch
spark stirrup
sage latch
#

wait idk

sage latch
#

its something like that

spark stirrup
#

Yes it is

#

you can also use ctrl+7

sage latch
rigid island
#

all the links are there tho

#

i aint google

#

lol

spark stirrup
sage latch
#

frame debugger shows you each render batch

#

i think its called that at least

mild karma
rigid island
#

you can like step through how your scene is rendered

spark stirrup
rigid island
#

yea thats a lot of dips

spark stirrup
#

Yep

leaden solstice
#

You have script/physics overhead as much as rendering

rigid island
#

Editor adds some overhead too iirc unless you do DeepProfile no? or standalone?

spark stirrup
#

besides the player

rigid island
#

ah ok that make sense

leaden solstice
cosmic vector
rigid island
#

not like Kinematic static, like gameobject.isStatic i think

cosmic vector
#

Tons of individual objects is part of your problem.

spark stirrup
spark stirrup
spark stirrup
rigid island
sage latch
#

I shouldn't affect physics though

leaden solstice
#

No Rigidbody = static collider

rigid island
#

yeah why is there physics on static blocks?

#

lol

cosmic vector
# spark stirrup How would I do that?

Take vertices from all cubes and put them in one vertex array. Take all triangles and build a new triangle array. Combine the materials from all the cubes so everything is colored correctly. Turn off the mesh renderer on all of the cubes leaving only the collider and then just render the big mesh.

#

You mentioned minecraft. It isn’t rendering hundreds of individual blocks. It renders “regions” of 16x16x16 blocks. Where a single mesh represents the region.

spark stirrup
#

Well i am currently

sage latch
#

When something changes in the chunk, you recompute its mesh

spark stirrup
#

Should I put all of the loaded chunks into one mesh, or just each chunk?

leaden solstice
#

Unity dynamic batching should handle it similarly if you set up your material properly

cosmic vector
#

Yep you’ll have to figure out how to combine those cubes into a single mesh in order to get decent performance.

leaden solstice
#

That’s why you look into frame debugger

sage latch
#

so only have to rebuild one chunk's mesh when you change it (place, destroy etc)

spark stirrup
#

Got it, i'll work on it and let you guys now how it goes 👍🏻

#

Thanks for the help everyone

scarlet kindle
#

Hey @rigid island one more question sorry to rehash this but I wanted to load the SO asset template into my deck, right? I know you said I could make one more class but I wanted to try it this way to do a POC

So I was thinking of trying https://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetAtPath.html
But! I read something in another article that said doing this is bad practice, is that true?

leaden solstice
scarlet kindle
#

ok so how would I load the templated asset into the deck then?

#

without the UI of course

rigid island
#

if you only want data

leaden solstice
#

If you need dynamic resource loading should look into Resources.Load

rigid island
#

make list of POCO if you want to store instances

rigid island
scarlet kindle
scarlet kindle
#

like Attack is a templated asset of the SO

rigid island
#

Attack is just a created asset from SO

scarlet kindle
#

ok so should I use Resources.Load to put that into my SO list? Cuz I don't want to deal with assigning their attributes every time.

rigid island
#

defeats the whole point tbh, you mind as well just toss all those into a list inside inspector

scarlet kindle
#

uhhh wait but the whole point is to be able to pop them off the deck into the hand right?

#

so i need script for that

#

or like if a user is adding cards to their deck in the game, or removing them etc

rigid island
#

your player can just deal with a list of your POCO that have the SO

#

keep those inside a List<Card> as your available cards

#

you can probably split that further into separate lists ig

#

public List<Card> AttackCards
public List<Card> DefenseCards etc..

scarlet kindle
#

ok

#

thanks a ton!

rigid island
scarlet kindle
#

yes and I see what you're saying, I guess I just wanted to load them in with code so I don't have to deal with all the annoying UI stuff

#

but i get that is only for a setup step

#

prior to the player doing anything or deck management/etc

rigid island
scarlet kindle
#

yea makes sense

sage latch
#

You might be thinking of AssetDatabase which can in fact only be used in the editor

rigid island
sage latch
#

I don't know about that

rigid island
#

Idk lol I never use it tbh never seen the needs for it.
If I need dynamic content I stick to the persistentDatapath , or like AssetBundle or addressables ? (forgot which one lol)

scarlet kindle
#

So I'm trying

public void addCard() { Card currentCard = deck.cardStack.Pop(); prefab.card = currentCard; GameObject cardGO = Instantiate(prefab); cardList.Add(cardGO); sortCards(); }

but issue is that the prefab's script contains the Card object, I don't know how to add the currentCard into it?

the 2nd line causes an error

scarlet kindle
#

'GameObject' does not contain a definition for 'card' and no accessible extension method 'card' accepting a first argument of type 'GameObject' could be found

which totally makese sense, I need to add the card to the prefab's script, not the GO itself

leaden ice
#

you generally should not modify prefabs

#

you should be setting the card on the newly instantiated card, right?

robust dome
#

prefab<GetComponent>().SomeScript.card = currentcard;

leaden ice
#

You should change:

public GameObject card;

tocs public CardHandler card; or whatever the Card prefab's script is called

#

that will make your life much easier

#

then you can do:

CardHandler newCard = Instantiate(prefab);
newCard.card = currentCard;```
rigid island
#

man you should really change that Card class to CardSo and make a POCO class for Card @scarlet kindle

scarlet kindle
#

yes I agree with you

#

@rigid island

#

it's really just a POC but maybe that's just shooting myself in foot

rigid island
#

huh whats POC

scarlet kindle
#

proof of concept

#

just to see if i can actually deal a card into the damn hand

#

lol

rigid island
#

yes but you have to deal with instances from SO never directly modify SO class

scarlet kindle
#

for the actual game will definitely need another class in between them

scarlet kindle
# leaden ice then you can do: ```cs CardHandler newCard = Instantiate(prefab); newCard.card =...

it's giving me conversion errors when I try to do that

I have

public GameObject prefab; public DeckScript deck; public List<GameObject> cardList;

and my code is

` prefab<GetComponent>().CardDisplay.card = currentCard;
CardDisplay cardPrefab = Instantiate(prefab);
cardPrefab.card = currentCard;

    cardList.Add(cardPrefab);`

and now complains on last line for type conversion from CardDisplay (script) to GameObject

leaden ice
leaden ice
#

oh sorry I made a typo I guess

#

public GameObject prefab; needs to be public CardDisplay prefab;

#

Also this line is incredibly confusing:
CardDisplay cardPrefab = Instantiate(prefab);
don't name this variable cardPrefab. It's not a prefab. A better name for this would be like cardInstance

scarlet kindle
#

the Resources.Load isn't working sadly. I added the Resources folder and follow the directions in the link, not sure

Card attackBasic = Resources.Load<Card>("Starting Deck/Attack");

#

could it be the space in the folder name?

scarlet kindle
#

The SO

leaden ice
#

That should work

#

Why do you say it's not working?

scarlet kindle
#

get an NPE when trying to reference the assigned object

#

Card attackBasic = Resources.Load<Card>("StartingDeck/Attack"); cardStack.Push(attackBasic);

somber nacelle
#

if that second line is throwing an NRE then it's actually cardStack that is null

scarlet kindle
#

omg

#

i feel so dumb

#

ty

#

maybe i need a little break... heh

spark stirrup
#

Does anyone know why my code is creating gaps inbetween the chunks?

private void UpdateChunks()
    {
        Vector2Int currentPlayerChunk = GetCurrentChunkPosition(player.position);

        foreach (var chunkPair in chunks)
        {
            Vector2Int chunkPosition = chunkPair.Key;
            if (Mathf.Abs(chunkPosition.x - currentPlayerChunk.x) > renderDistanceInChunks ||
                Mathf.Abs(chunkPosition.y - currentPlayerChunk.y) > renderDistanceInChunks)
            {
                chunkPair.Value.SetActive(false);
            }
            else
            {
                chunkPair.Value.SetActive(true);
            }
        }

        for (int x = currentPlayerChunk.x - renderDistanceInChunks; x <= currentPlayerChunk.x + renderDistanceInChunks; x++)
{
    for (int z = currentPlayerChunk.y - renderDistanceInChunks; z <= currentPlayerChunk.y + renderDistanceInChunks; z++)
    {
        Vector2Int chunkPosition = new Vector2Int(x,z);

        if (!chunks.ContainsKey(chunkPosition))
        {
            GenerateChunk(chunkPosition);
        }
    }
}


    }

scarlet kindle
jolly crag
#

what is the relationship between scale and position when using the rect tool in unity?

jolly crag
#

Yeah in the editor

leaden solstice
#

I mean UI canvas

jolly crag
#

Yeah

leaden solstice
# jolly crag Yeah

Don’t use scale for UI elements because anchoring does not account scale. Position you see is anchoredPosition relative to anchor

elfin tree
#

What happens if I Serialize, save to a file, then load a Serializable ScriptableObject that has all of it's fields private. Will it still work as a reference of the ScriptableObject within the project assets? Or since the fields are private, will it be incomplete?

leaden ice
elfin tree
leaden ice
#

alright and what does that have to do with all the serialization stuff you mentioned

elfin tree
leaden ice
#

if it will properly load as that specific instance, from the file
it's definitely going to not be that specific instance. It's a copy.
or if it will be an incomplete version of it since it's fields are private (meaning not serialized afaik).
This depends highly on which serlaization mechanism you are using and whether there are any attributes on the field. For example Unity's serializer will serialize private fields if you have [SerializeField] on them

elfin tree
#

Oh okay, should be fine then, they all have [SerializeField]

leaden ice
#

hwo are you serializing?

#

With Unity's JsonUtility?

elfin tree
quasi python
#

Hey, I'm trying to make a player movement script that reduces the amount of control a player has while in the air. Does anyone know how to do this?

leaden ice
quasi python
#

right, I have that, but what formula would I use?

leaden ice
#

entirely up to you?

quasi python
#

that's the problem, I can't figure it out

leaden ice
#

you haven't exactly provided any specifics about what differences you want

#

so it's just a game design problem at the moment

#

figure that out first

#

then think about the code

lean sail
#

I'd hardly even say u need a formula. Literally just multiply or divide by something

elfin tree
quasi python
lean sail
#

So the control you want is to not allow the player to change direction?

quasi python
leaden ice
quasi python
leaden ice
#

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

quasi python
#

!code
float dirX = Input.GetAxisRaw("Horizontal");

    if (IsGrounded())
    {
        rb.velocity = new Vector2(dirX * movementSpeed, rb.velocity.y);
    }
    else
    {
        //to be determined
    }
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.

leaden ice
#

not type that

quasi python
#

        if (IsGrounded())
        {
            rb.velocity = new Vector2(dirX * movementSpeed, rb.velocity.y);
        }
        else
        {
            //to be determined
        }```
leaden ice
# quasi python ``` float dirX = Input.GetAxisRaw("Horizontal"); if (IsGrounded(...
void FixedUpdate() {
  float dirX = Input.GetAxisRaw("Horizontal");

  if (IsGrounded())
  {
     rb.velocity = new Vector2(dirX * movementSpeed, rb.velocity.y);
  }
  else
  {
     Vector2 targetVelocity = new Vector2(dirX * movementSpeed, rb.velocity.y);
     rb.velocity = Vector2.MoveTowards(rb.velocity, targetVelocity, Time.deltaTime * 2);
  }
}``` something like this
quasi python
#

what does 'addforce' do?

leaden ice
#

nvm I changed it

#

forces will add a bunch of complication here if you want speed limits etc

quasi python
#

so with this script, can you change how much control you have while in the air?

leaden ice
#

yes

#

by changing the 2 here: Time.deltaTime * 2

quasi python
#

so do higher or lower numbers give you more control?

leaden ice
#

what do you think

quasi python
#

higher, I got it

robust dome
#

btw how does your isGrounded bool look like

#

you have to code that too right

quasi python
#
    {
        return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, 0.1f, jumpableGround);
    }```
robust dome
#

k

rigid island
#

!code

digital crater
#

My player will not move left or right

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.

rigid island
#

Larrge Code 👆

digital crater
#

Yeah I figured it out

rigid island
#

ok for next time then

digital crater
#

Thanks

#

But yeah, my player will not move at all

#

And I can't figure out what's wrong with it

rigid island
#

you said you figured it out ?

digital crater
#

No, I figured out how to display the code like code

rigid island
digital crater
#

Ohhhhhhhhhh

#

Here ya go

#

My player will not move at all. Any suggestions?

rigid island
digital crater
#

No

rigid island
digital crater
#

I have colliders (the "Player" is an empty for 6 different parts of my player)

rigid island
#

do you see rb moving

rigid island
#

on player

digital crater
rigid island
#

forgot how 2d rb works

digital crater
#

I'll give it a shot

#

Nothing

rigid island
digital crater
#

The animations work perfectly though

rigid island
digital crater
#

Hold up

#

Now you say that.. lemme try something

strong nimbus
#

Hi. I am trying to hover an object. But when I start the game it jumps up a bit on the Y axis and THEN hovers perfectly. No matter what I have tried I can't make it not do the initial jump. Like, the original position is -100 on Y. It jumps to like -20 or something, then hovers between let's say -26 and -36 or whatever. What is making it jump up 70 ish units on the y axis?


public class UIHover : MonoBehaviour
{
    public float hoverHeight = 1.0f;       // Height of the hovering motion
    public float hoverSpeed = 1.0f;        // Speed of the hovering motion

    private Vector3 initialPosition;

    private void Start()
    {
        initialPosition = transform.position;
    }

    private void Update()
    {
        Hover();
    }

    private void Hover()
    {
        float yOffset = Mathf.Sin(Time.time * hoverSpeed) * hoverHeight;
        Vector3 newPosition = initialPosition + new Vector3(0, yOffset, 0);
        transform.position = newPosition;
    }
}

strong nimbus
#

yeah

knotty sun
#

so it's initial position will be controlled by the RectTransform and the anchors used

west pelican
#

man i was doing so well

#

i had finally figured out how make my character face a direction without actually movign it unless the key was held for a certain amount of time

#

but now the animation is bugging

strong nimbus
west pelican
#

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

west pelican
#
 private void Update()
 {
     move = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
     print(anim.GetBool("moving"));
 }

 private void FixedUpdate()
 {
     if (move == Vector2.left || move == Vector2.right || move ==  Vector2.up || move == Vector2.down) 
     {

         if (move.x > 0)
             anim.SetTrigger("facing right");
         else if (move.x < 0)
             anim.SetTrigger("facing left");
         if (move.y > 0)
             anim.SetTrigger("facing up");
         else if (move.y < 0)
             anim.SetTrigger("facing down");

         moveTimer += Time.deltaTime;

         if (moveTimer > moveBuffer)
         {
             rb.MovePosition(rb.position + move * speed * Time.deltaTime);
             anim.SetBool("moving", true);
         }
     }
     else if(move == Vector2.zero)
     {
         moveTimer = 0f;
         anim.SetBool("moving", false);  
     }
 }
#

this is my code for the movement

#

basically if you input a direction (left, right, up, down), the player will face the direction you pressed, and if you hold it down for a certain time (moveBuffer), it will start walking in that direction

#

my issue is that for some reason the animation keeps jumping back and forth between the idle and moving animation

#

each direction has an idle and walking animation

#

and the transition from idle to walking is if the boolean "moving" is true, and the transition from walking to idle is if "moving" is false

#

but for some reason the animation jumps back and for between moving and idle

#

can anyone help me?

vagrant blade
#

Though, generally speaking, this could be cleaned up a bit. But get it working first.

west pelican
#

yeah i know this probably isn't optimal lol. i'm just starting out. lemme do ur suggestions rq

#

what do you mean by that first poitn?

#

point*

#

i want the player to face the direction before they move

vagrant blade
#

Which happens while the timer is less than the buffer. The check you should be adding will only verify that and prevent it from being set once the buffer is reached.

west pelican
#

ohhh

#

like this

#
            if (moveTimer < moveBuffer)
            {
                if (move.x > 0)
                    anim.SetTrigger("facing right");
                else if (move.x < 0)
                    anim.SetTrigger("facing left");
                if (move.y > 0)
                    anim.SetTrigger("facing up");
                else if (move.y < 0)
                    anim.SetTrigger("facing down");
            }
#

ok so that parts good now

#

now there's a new issue 😭

#

ignore the music i forgot to pause it ☠️

#

basically now the player doesnt change direction until we stop moving

vagrant blade
#

Because you're not resetting the move time between directions (which you don't want or there will be a pause). But your animator has no way to transition to another move animation if it's already running a different move animation.

#

Quick hack would be to hook your move states to the any state as well. But you can see how you're getting into messy territory.

west pelican
#

yeah i feel like that could also start problems

#

so the only solution i see is making transitions between all of the moving animations

#

but that feels tedious

vagrant blade
#

Try the Any State option

west pelican
#

alright

#

and delete the transition from the idle to the walkign animations?

vagrant blade
#

Yep. Leaving it shouldn't be an issue, it's just redundant.

wintry crescent
#

why does something like this:

[HideInInspector]
[field: SerializeField]
public virtual bool ShowSingletonErrors { get; protected set; }

still show up in the inspector? I verified that there are no errors and the code compiled

#

it looks like [HideInInspector] is ignored for fields?

west pelican
wintry crescent
west pelican
#

oh jeez this did not work

leaden solstice
vagrant blade
leaden solstice
#

Mecanim makes me sad

west pelican
wintry crescent
# leaden solstice You are putting `SerializeField` attribute on field, so should `HideInInspector`...

[field: HideInInspector] works, as I really should have guessed
I'm just making a generic singleton<T> class, and I wanted a way to choose, when writing the code of a deriving singleton class, if the errors like "singleton already exists" or "destroying an object with a singleton" should get displayed with Debug.LogError
now all someone needs to write is
public override bool ShowSingletonErrors { get { return false; } }
in their class when deriving from my singleton class, and the errors will be gone

vagrant blade
#

Well, you'll need to start debugging the states I suppose.

wintry crescent
#

and I thought that setting it in inspector is cluttering it up

west pelican
#

it faces the directions fine, but once i start moving it plays the walking_up animation over and over

leaden solstice
west pelican
#

maybe because it's the "last" transition, so since the walking animation can come from any state, the animation just transitions to walking_up

wintry crescent
west pelican
#

do transitions take priority?

leaden solstice
vagrant blade
#

You will need to set unique parameters for the moving direction, the same way you're doing for idle.

west pelican
#

oh

vagrant blade
#

Because if they're all sharing the same parameter, it won't know which you actually want.

west pelican
#

that's true

leaden solstice
#

Any state will keep evaluate to current state and start transition

west pelican
#

is it "Can transition to"?

leaden solstice
west pelican
#

oh

#

yeah

#

got it

#

its so confused 😭

leaden solstice
#

Because it'd be just method call

west pelican
#

it made up a whole new animation because it keeps switching from walking_up to walking_right

#

the frame rate is too fast for obs ☠️

wintry crescent
west pelican
#

its in between up and right

west pelican
#

hmmm

#

transitions can take multiple conditions to trigger right?

leaden solstice
#

Yeah

west pelican
#

IVE GOT IT

#

well i have an idea

#

i will make the transitions from any state to idle have 2 conditions

#

its facing a direction and moving == false

#

and from any state to walking, it needs to face a direction and moving == true

#

then i will get rid of the if statement checking if the moveTimer < moveBuffer

#

because i need the direction to be able to update while moving

#

and the animation switching glitch shouldnt happen because idle will need moving to equal false

#

IT WORKED

#

MWAHAHAHA

#

IM A GENIUS

#

now. next step

#

make it so i can go diagonally

west pelican
#

right now what happens is if i press down 2 keys at once, the player stops and it plays the idle animation for one of the directions im holding down

dark kindle
#

if only we were able to set a scene of a game object as easy as go1.scene = go2.scene; or go1.SetScene(go2.scene);

#

my life would be easier

dark kindle
#

thanks, i think this could work for my application

stable osprey
#

thinking back, there's no way I would approve the left version, but I'd approve the right with some additional comments 😅 I'm starting to get worried

spark stirrup
cosmic rain
cosmic rain
# spark stirrup

I see that you don't know how to use the profiler. That screenshot provides 0 useful info.
Look up resources on how to use the profiler or read the manual.

pure onyx
#

Hello i wanna ask. I wanna snap gizmo in unity editor. I use Handles.FreeMoveHandle to snap the gizmo but i must press ctrl on keyboard. Can i snap gizmo without pressing ctrl on keyboard ?

burnt temple
#

i'm just dumb

cosmic vector
# spark stirrup I'm lost on how to actually do this. The texturing stops working when I try this...

You have too many game objects because you have every single cube being a game object.

That graph you posted looks like around 1/4 of the time per tick is spent on scripts. Presumably because you have a script on every block.

1/4 of the time is spent on rendering. Presumably because it is having to determine which blocks are visible.

1/4 of the time is spent on physics. Presumably because you have tons of colliders.

Merging them into a single mesh doesn't only solve rendering.

muted schooner
#

Just a suggestion

west pelican
#

yeah i figured it out

#

basically i have a bool "moving" and 4 triggers, one for each direction

#

and if "moving" is true, the character will walk in whatever direction was triggered

#

and if it is false they will stand still facing whatever direction was triggered

muted schooner
#

I somehow don't like the unity animator stuff, they are weird

west pelican
#

i would do that but i dont wanna fix what aint broke

muted schooner
#

Yeah you are right, just saying to let you consider in further projects

west pelican
#

my code is functional, even though it probably isn't optimal, its the best i can do at my level

#

yeah i'll try it out on my next thing

#

and the movement is surprisingly smooth so yay me

gilded edge
#

Whats the point of interfaces i dont need something telling me that i need this its either i have it or not

broken light
#

how do you enable unsafe in unity

#

trying to do some memory copying seems i need to enable it some where

burnt temple
#

i forgot tho...

broken light
#

very helpful lol

cosmic vector
cosmic rain
broken light
#

ah finally found it

spring creek
supple hinge
spring creek
supple hinge
#

im getting confused rnatwhatcost

spring creek
supple hinge
#

maybe im tired

#

thank you Aeth

#

gn

cosmic rain
#

It could be a custom class. There's no knowing that without seeing the author's project.

brave musk
#

Quick question - when you set the time in a timeline playable, does it traverse the tree and set the time for each of the playables in that timeline's subgraph?

gilded edge
gaunt iris
#

This isn't really coding, but I don't see a more relevant channel:
How expensive are mesh colliders really? My scene is covered in them, and I don't really see an alternative to have traversal on and around these meshes feel good

#

Is there a way to use collision brushes etc to manually setup scene collision to optimise this? (Like in Source Engine)

cosmic vector
gilded edge
#

The only reason i can see myself ever using interfaces is grouping classes together inheritance abstraction and interface always confuse me

cosmic rain
#

Interfaces differ from to other in the sense that they separate API from the implementation.
Interface is a contract that tells you that the class implements a certain API, but it doesn't reveal anything about the implementation itself.

#

Base class promises that there is at least a basic implementation. Unless the method is abstract. In this case it is almost the same as an interface, except that you can only inherit from one base class, while implementing multiple interfaces is possible.

gaunt iris
quartz folio
#

That is a fairly new thing to C#, so it will exist depending on what Unity version you use.

leaden solstice
wintry crescent
#

if I have something like

newObj.transform.position = Vector3.zero```
will Awake functions on scripts in newObj be called before, or after setting the position to Vector3.zero?
Or to form my question differently, does Instantiate internally call Awake on all scripts attached to the spawned object? Or is it called during the main loop, on the next frame
wintry crescent
quartz folio
#

Same iirc

wintry crescent
#

ah
my goal is to have something that will be call after that, but before the Start() on other scripts on that object

quartz folio
leaden solstice
#

Start will be called on next frame

tame iris
#

How to open specific folder in default file manager app(android)?

#

'DCIM' folder

leaden ice
celest iron
#

What is the difference between CapsuleCast and CapsuleCastAll?

tame iris
quartz folio
celest iron
#

Thank you

gaunt iris
#

Is it okay to set Rigidbody velocity in Update() rather than FixedUpdate?

#

Moving objects around in VR is a jittery mess with fixedupdate

#

But I know physics is ran on fixedupdate

leaden ice
celest iron
#

Read the input in the update, then move in fixedupdate

leaden ice
gaunt iris
#

It's the XR toolkit

celest iron
#

Oh

#

Yeah, i don't know much about XR

leaden ice
#

You need to enable Rigidbody interpolation to make it not jittery

#

It has nothing to do with XR

celest iron
#

Btw, talking about physics, is it performance heavy to use CapsuleCastAll?

gaunt iris
celest iron
#

In the character, constantly looking for collisions

gaunt iris
#

As obviously before fixedupdate hits it has no info on current position

leaden ice
gaunt iris
#

So it's always behind by an update cycle at worst

#

It basically lags, without stuttering

#

The fix I've seen online is parenting the object to the player hand object

#

And I don't quite understand how physics can still work correctly like that

leaden ice
#

It can't

tame iris
# leaden ice It's for Android. Look up how to run native android code from your Unity app

so, there is no way to do it with c#?

I have tried this and it does nothing.

AndroidJavaClass jc = new AndroidJavaClass("android.os.Environment");
string path = jc.CallStatic<AndroidJavaObject>("getExternalStoragePublicDirectory", jc.GetStatic<string>("DIRECTORY_DCIM")).Call<string>("getAbsolutePath");

    // Get the path of the folder you want to open
    string folderPath = Path.Combine(path, "Game Screenshots", "Map 1");

    // Create an intent to open the file manager
    AndroidJavaClass intentClass = new AndroidJavaClass("android.content.Intent");
    AndroidJavaObject intentObject = new AndroidJavaObject("android.content.Intent", intentClass.GetStatic<string>("ACTION_VIEW"));

    // Set the URI to the folder's path
    AndroidJavaObject uri = new AndroidJavaClass("android.net.Uri").CallStatic<AndroidJavaObject>("parse", "file://" + folderPath);
    intentObject.Call<AndroidJavaObject>("setDataAndType", uri, "resource/folder");

    // Get the current Unity activity and start the intent
    AndroidJavaClass unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject unityActivity = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity");
    unityActivity.Call("startActivity", intentObject);
leaden ice
#

The typical approach is a proxy physics object that follows the XR moved object

celest iron
gaunt iris
#

This thread seems to suggest you can get away without it

#

Does physics still work properly if a parent of the object has its transform changed?

#

I'm assuming not

celest iron
#

@leaden ice is it bad to use CapsuleCastAll to check for collisions? I'm afraid it can get laggy

leaden ice
#

Don't ping people outside the conversation

celest iron
#

Oh ok

#

Sorry

#

Anyways, question still stands for other people I guess

#

Are constant cchecks with CapsuleCastAll bad?

lean sail
celest iron
#

I do, yeah

lean sail
#

You should state what the actual problem is, so people can tell if theres a better way.

celest iron
#

So, I want to make a controller for my character, but he is kinematic. I want to check for collisions using CapsuleCastAll. The thing is, I've read somewhere that doing those casts are bad and I should find an alternative.

#

Tho I can't think of anything else to check for collisions

#

You know what? Nvm, I'll just deal with it later if any problems arise

#

If everything is bad to performance then there wouldn't be any games at all

gaunt iris
celest iron
#

True

lyric moon
#

how can i get the rotation speed of a transform?

#

i wanna know how fast a transform is rotating

prime sinew
cosmic rain
lyric moon
lyric moon
cosmic rain
#

Sure there is.
rotation speed = (rotationB - rotationA)/ time between B and A.

lean sail
#

for euler angles sure, if you're trying to do it based on quaternions itll be a bit more math

mellow sigil
#

You already have the rotation speed, it's the amount you're rotating it by (divided by deltaTime)

slim vine
#

heyo, so I'm trying to make a custom cursor for my top-down game, that is like an arrow that points away from the player character towards the mouse (so the cursor needs to rotate, basically).

I've created a UI element that follows the mouse via a script, but there's a frame delay between the actual cursor and the custom cursor.

Is there a way that I can script my "UI cursor" to update its position immediately with changes to the hardware cursor? I can't think of a way that'd be possible, but I figured it wouldn't hurt to ask.

I've also investigated using a virtual cursor to override the hardware mouse... but from my understanding, this means the actual game cursor would still have the frame delay. Is there a way around this delay? Is the frame delay noticable, in your experience?

The complication here is that I'm designing a sort of twitchy game and don't want to worsen the player experience...

leaden ice
#

Maybe make 8+ cursor textures for directions and swap them out?

elfin quest
#

If somthing does not work as intended, don't fix it, make it intended!

#

goosebumps

slim vine
#

Unfortunately I'm looking for 360 degrees of smooth rotation, (that's a lot of sprites!), I don't think I can tangibly do that... In theory I guess I could somehow procedurally generate them?

I think I'll just investigate implementing a virtual cursor and see how it feels

tired elk
#

You just want an arrow that orbits around your character ?

slim vine
#

But in principle I think the sprite sheet style approach would work

leaden ice
#

What style game is this?

slim vine
#

Top down melee slasher

#

Some experiment I'm working on

tired elk
#

Why don't you use a simple sprite with a pivot centered on your character instead of making it this complicated ?

#

Juste hide the cursor if you don't want the pointer to be visible

slim vine
#

Would that allow me to move the cursor closer or further away? I'm not familiar with that approach, still kind of a unity noob

slim vine
#

I don't want to hide the cursor because if the real cursor is still doing the clicking it will be weird when interacting with things

slim vine
#

(i think)

leaden ice
slim vine
#

theres another design complication here

#

which is the little spike going down from the cursor

leaden ice
#

Maybe not since Diablo 2? I don't recall

slim vine
#

that indicates left/right side attack direction

#

(think like Mordhau)

#

so uhh... double... triple the sprite count for the spritesheet mouse 😄

leaden ice
#

Yeah that's not gonna be feasible with hardware cursor

elfin quest
#

But if you want the cursor to face the character you could go with camera.ScreenToWorld() look it up I don't recall exactly the usage, calculate the angle from that point to the player and use that angle to rotate your cursor no?

slim vine
#

you can rotate the hardware cursor sprite?

leaden ice
#

I would recommend Plane.Raycast for this POV

slim vine
#

i've been doing the camera stuff

#

i think the most sensible approach might be to just use a virtual cursor to command the UI, and hide the actual cursor

#

(and have the frame delay)

#

also i guess thats necessary for controller support?

#

(OR just scrap this questionable design entirely and come up with a better way of indicating things)

#

regardless, thanks for the help, everyone 😄

leaden ice
#

I'd look at Baldurs Gate 3 and Divinity Original Sin 2 for inspiration

#

They have a hardware cursor and lots of corresponding software particles and indicators integrated nicely

slim vine
#

Oh! I actually haven't even considered thinking about how games deal with this. WELP now I can't play games without screwing around with the cursor to try and tell if it's hardware or not

#

Thanks for the inspiration, will definitely mess around with the bg3 cursor 😄

#

This design challenge seems to be quite valuable

void remnant
#

Hello, after I create a Scriptable Object with .CreateInstance(), do I need to make it a .asset file? (with asetDatabase.CreateAsset) I don't want it to see it in my asset files, but i'm scared it will get deleted

crude haven
#

I have a question relating map if anyone know how to solve it somehow, I have a map with edit function which you can add markers into it, and then u load it out (through location data), are there any way i can anchor the markers so it stay the same on different resolution? Cause atm when i load it out using theirs local position, the location will be wrong because map is resized on different resolution but markers aren't

leaden ice
void remnant
#

if I won't save it as an asset, will it get deleted?

leaden ice
#

It won't get deleted so much as it will never have been created in any persistent sense

tired elk
#

Well, do files get deleted if you don't save them ?

void remnant
#

hm

#

so if I have a list in an editor window somewhere with a scriptable object that's not saved as an asset, if I close and open the game, it will be deleted?

tired elk
#

You'll lose the SO with the data it contains, yes.

void remnant
#

ok

#

thanks

swift falcon
#

Something random when you are about to finish your project and upload your game are you guys using smthing for anti cheat?

knotty sun
vague tundra
#

Hey guys.
I am trying to re-order children of a prefab. I am getting the following error:
"Children of a prefab instance cannot be deleted or moved, and components cannot be reordered"

I am trying to re-order children of the prefab itself - not an instance of a prefab.

Any thoughts?

prime sinew
#

if it's in your scene, it's an instance

#

you need to double click the prefab in your asset window to go into prefab mode and change it there

vague tundra
#

Like I said, I'm modifying the prefab itself, not the instance of it

#

Trying to move 'Blocker' above 'InteractionArea'

prime sinew
#

the non variant

vague tundra
#

Sorry I'm not following, what's the non-variant?

prime sinew
#

this is a variant

#

click on the > beside Door

vague tundra
#

Ooooh interesting

prime sinew
#

you cannot modify BasicInteractable's hierarchy which Door has inherited

#

so that's why

vague tundra
#

Awesome, tyvm!!

prime sinew
tired elk
#

You're working on a prefab variant, so it has to respect the base prefab hierarchy

#

(for some reason, my window didn't show more recents messages...)

vague tundra
#

Awesome, cheers:D

knotty sun
#

<@&502884371011731486> Offensive user name

opal cargo
#

Hi guys, is there a "best practice" in creating classes for a player controller?
I.e. my Character consists more or less of 3 scripts - a Cam-Manager that manages rotation, a Kinematic Character Controller that handles the movement input and rotates with the rotation of the cam and a weapon manager, that controles weapon selection, firing and the zoom.
So when I want to zoom, my WeaponMgr recognizes the button press and sends an event to the Cam Manager (over main player class) to start zoom with parameters given by the weapon object.
When my Character slides down a slope, the KCC sends a signal to Cam to restrict rotation angles, so my Character can only look down the the to a certain degree.
Is this "the right way" to handle communication between such entities, is there another State Machine in between that syncs and handles stuff more appropriate? Maybe I'm just stuck in a analysis paralysis but synchronizing all 3 becomes a bit hard to oversee...

mellow hill
# opal cargo Hi guys, is there a "best practice" in creating classes for a player controller?...

This seems like a good approach to maintain SoC (Separation of Concerns), if you wanted to classes your have less of a direct dependency on the player class, you could utilise events (look into the Observer pattern) and that would be a good way for your scripts to communicate while being further decoupled (this makes it easier to change classes/requirements without needing to have hard dependencies between classes when communicating). There are multiple approaches/patterns that you could use for your use-case though

rough sorrel
#

Hi. One question, what is wrong with this code because it doesn't matter which button I press it always debugs the same value please:

 for (int i = 0; i < Tabs.Count; i++)
            {
                TabsButtons[i].onClick.AddListener(() => Debug.Log(i) );
                TabsButtons[i].onClick.AddListener(() => SelectTab(Tabs[i]));
            }
lean sail
sleek bough
hollow dune
#

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

hollow dune
#

Hello! I've got an issue with my character. I make him jump by increasing his velocity, and if the button is pressed long enough he will jump higher. However, if after dashing I'm still pressing the jump button, the character will conserve the momentum it got before dashing.
I'd be really glad if you knew how to help me with this! Thank you before hand
If you need me to show any code, feel free to ask :)

prime sinew
#

Please just show the code before being asked. This is most likely a code issue

hollow dune
#

I've fixed the issue with another method, thank anyways, as your advice was useful as well ^^

prime sinew
#

Is there still an issue? @hollow dune

hollow dune
#

Nope! What I did, was to change the variable that measured the timer for the press while jumping, to 0, when the dash started.

#

So, when the dash finished, that timer would be 0, so it wouldn´t go up anymore

prime sinew
#

okay

opal cargo
#

Got another question btw, how do you guys handle animations in your code?
I have specific movements that solely rely on calculations rather than Input (i.e. climbing up a ledge, which calculates an end-position and moves the Character via an animation curve).
Do I just play a real animation while my player object is moving via an animation controller or how is stuff like this handled properly?

mellow hill
# opal cargo Oh yeah, the observer pattern, I remember it 🙂 I'm beginning to become a bit co...

There is a book on game programming patterns which covers the some useful ones for game development such as command, observer and state pattern. It also wouldn't hurt to look into the SOLID priniples in my opinion. You don't have to follow them religiously but each principle builds on one another and can be a good way to think about code architecture. While they are a lot of good resources about SOLID, this is a good playlist for applying those concepts within Unity: https://www.youtube.com/watch?v=Eyr7_l5NMds&list=PLB5_EOMkLx_WjcjrsGUXq9wpTib3NCuqg

Check out the Course: https://bit.ly/3i7lLtH


Learn how to apply the SIngle Responsibility Principle (the first of the SOLID Principles) to your Unity3D game. We'll start off with a sample that violates SRP completely, then dive into how it can be refactored to be clean and maintainable.

More Info: https://unity3d.college/2017/01/10/u...

▶ Play video
mild karma
#

Has someone with riderflow also came accross this error: Assertion failed on expression: 'manager != NULL' when loading a scene in play mode? It doesn't affect the game itself, but it's weird that it keeps happening every time. Here's the full stack trace: https://hastebin.com/share/qituxezefa.xml

opal cargo
# mellow hill There is a book on game programming patterns which covers the some useful ones f...

Already know his videos, Jason is pretty good for this stuff 😄
Just wonder if my approach is "the right one" or if there's an easier solution, so I don't have to re-invent the wheel.
Like how do I move a character along a given path with proper animation (like my climb example)? Wonder if I'm doing it "the right way" by lerping my character position and playing an animation in the meantime using my animation controller.

wintry crescent
opal cargo
#

Invoke 1000 UnityEvents and C# Events, compare the time needed, be surprised 😄

dawn mauve
opal cargo
dawn mauve
opal cargo
dawn mauve
steady moat
opal cargo
steady moat
opal cargo
steady moat
opal cargo
steady moat
opal cargo
#

Hmm, good point

steady moat
#

If you want to have a camera that has a close connection to the controller, I would make a specific Controller Camera.

#

Then, you could take the most of the logic out of the player and use this component instead.

#

Also, the Controller Camera would probably use a standard camera. The difference is that it would be able to listen on the change of the controller and change the behavior of the camera.

#

Note, that would be overengineering at this step. Having everything in player is better for the moment.

opal cargo
#

OK, so PlayerClass needs to observe the States of my CharacterController and change the camera accordingly?

steady moat
steady moat
opal cargo
#

Sure, those are not my exact class names, was just for the diagram 😉

vocal kite
#

Hey guys, how can I adjust the text transparency in unity?
Thanks

prime sinew
#

what component is this

vocal kite
prime sinew
#

and do you mean you want to set the transparency through code?

vocal kite
prime sinew
#

you see there's a color field?

vocal kite
#

yeah i can see that

prime sinew
#

yeah

#

click it

#

what do you see

#

@vocal kite

vocal kite
#

my project is still loading

prime sinew
#

Already almost done with them

prime sinew
#

You just wasted the time of others

vocal kite
#

i know
my project just crashed

#

sry

prime sinew
#

anyway the color field has an alpha value you can change

#

that's all

vocal kite
#

thanks

frail turtle
#

hello,
i need a little insight help if possible:
i've coded my object to shoot a target, so at first i'm able to exactly shoot toward the target and it was working fine
but once i've modified the target to be able to move randomly, the bullets go toward old target position instead of new target position, is there someone who can explain/simplify how i should target a moving object or how my bullets reach its exact position ? thanks

rigid island
#

Gonna have to share the code

#

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

frail turtle
#

that's how my bullets are shot (this block is inside a bigger one in a coroutine):

 bullet.transform.LookAt(_selectedAlien.transform);
 Vector3 directionToAlien = (_selectedAlien.transform.position - bullet.transform.position).normalized;
 float bulletSpeed = 100f;

 Rigidbody bulletRigidbody = bulletProjectile.GetComponent<Rigidbody>();
 bulletRigidbody.velocity = directionToAlien * bulletSpeed;

and as i said, the targetted object moves towards a random point at a constant speed

rigid island
#

can you show hierarchy as well for the target

potent scarab
#

how to solve white border

frail turtle
#
private void MoveToPosition()
  {
      if (_targetPosition != _transform.position)
      {
          Vector3 currentPosition = _transform.position;
          Vector3 moveDirection = (_targetPosition - currentPosition).normalized;
          Vector3 movementVector = moveDirection * (movementSpeed * Time.deltaTime);
          Quaternion targetRotation = Quaternion.LookRotation(moveDirection, Vector3.up);

      
          if (_rotationMode == RotationMode.Free)
          {
              _transform.rotation = Quaternion.Slerp(_transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
          }
          _rigidbody.MovePosition(currentPosition + movementVector);

          CheckReachedDestination();
      }
  }
frail turtle
rigid island
frail turtle
#

i truly don't understand exactly

#

the class or order of execution or what

tired elk
#

The object your script is attached to. Hierarchy = the object and its children in the hierarchy view in Unity

frail turtle
#

ah okay

#

i don't think it'll help but sure (i'm pretty sure the above codes are enough):
the bullets spawn outside of the object (so that they will be independent of it) and then go toward target, nothing more nothing less
i'm just asking for the logic that helps identifying the correct position of a moving target, but google is giving me complicated math formulas and youtube isn't helping as well

rigid island
#

ofc it wont help.

#

I asked the hirerchy for the TARGET

#

How will it help? Since I don't have eyes in your screen, I could at least tell you're moving the target and not potentially a child object or something else you're not seeing.. Idk your setup so its only a minimum we should see the setup, scripts alone cant help without knowing the context they're in

dark kindle
#

how do i reference a script component with a public int? I tried go.GetComponent<Script>().num=1; where num is the public int value in the script of gameobject go.

rigid island
leaden ice
#

assuming you use the real identifiers for things

#

Highly recommend saving the reference in a variable rather than calling GetComponent all the time though

rigid island
#

hopeully its inside a method too 😛

dark kindle
dark kindle
tired elk
leaden ice
frail turtle
leaden ice
#

Customer: "My car doesn't work, fix it"
Mechanic: "Ok what's wrong with it?"
Customer: "It doesn't work"
Mechanic: "???"
Customer: produces a horse

rigid island
#

lmao

frail turtle
#

it doesn't have any hierarchy, it's literraly spawned directly on the scene

rigid island
dark kindle
rigid island
#

oh we're dealing RPC

dark kindle
#

says is unknown symbol

leaden ice
#

"Script"?

rigid island
leaden ice
#

Is your script actually called "Script"??

dark kindle
#

"Script"

leaden ice
#

Why would you write "Script" there

#

What is your script actually called

dark kindle
leaden ice
#

and if this is your level of C#/Unity knowledge you're making a mistake trying to make a networked game already.
You're trying to run an olympic marathon before you know how to crawl

frail turtle
rigid island
#

any Monobehavior can be a "Component"

terse garnet
#

guys, I'm trying to validate the touch block in the mobile touch UI so that it doesn't recognize a certain function if clicked on in the UI, I'm using this code snippet but it's not working, can you help me?

dark kindle
steady valve
#

does anyone konw why this happen? it just says something went wrong

rigid island
leaden ice
rigid island
#

you might be net blocked or firewall

dark kindle
frail turtle
rigid island
frail turtle
#

it's in a coroutine

leaden ice
frail turtle
#

nope

frail turtle
rigid island
frail turtle
#

on mouse click

rigid island
#

_selectedAlien.transform

frail turtle
#

just add the ref to the object in a private member

#

so i'm supposed to have the object ref when it's selected, which it is, but the lasers get shot at instant t and then the object move to t+1

#

and because it takes "a while" for lasers to reach the object so they reach the old position

rigid island
#

you said a coroutine right

frail turtle
#

ah wait, i mean, i click only to select, but when i shoot i click on a keybutton

#

like to enable/disable shooting

rigid island
frail turtle
#

kinda messy but

rigid island
frail turtle
#

yes

rigid island
frail turtle
#

okay i've found the solution

#

i only needed to update the target position on the bullet prefab

#

and adjust velocity and direction

rigid island
frail turtle
supple hinge
#

what's the difference between doing this

#

and this

tired elk
#

== is comparison, = is assignation

supple hinge
#

oh

#

angerjoy i forgot

spring creek
#

Also, the gameObject property is readonly pretty sure. Or a private setter public getter (the former makes more sense, but idk). You cannot assign to it

tribal gust
#

i am trying so that when the goes over a platform, there is a message in console saying "hit", but i just cant seem to get it right? can anyone help me?

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

public class DetectPP : MonoBehaviour
{
    public GameObject pp;
    private void OnTriggerEnter(Collider other)
    {
        Debug.Log("hti");
    }
}

the script is attached to the player and pp is the object i want it to hit

lucid wigeon
#

How do I debug XCode Simulator instance or app running in iPhone? I have a case where I click and do some raycast check. And this works for me in Unity, but not in XCode Simulator or iPhone. The XCode build is totally unreadable to me.

leaden ice
digital crater
#

@rigid island Continuing from the error yesterday - the velocity is being registered, but the player is not moving

rigid island
rigid island
leaden ice
# tribal gust

looks fine to me. Are you sure the colliders are overlapping?

digital crater
leaden ice
digital crater
#

as you can see....

rigid island
rigid island
#

or its moving something else

#

is Player child of anything ?

digital crater
digital crater
rigid island
#

I said child not parent

digital crater
#

Oh sorry. No, "Player" has no parent

leaden ice
#

try disabling it for a minute

digital crater
#

Disable the animator?

tribal gust
digital crater
#

Ok

digital crater
#

@leaden ice You are a genius

digital crater
leaden ice
#

classic mistake

#

move the renderer that it's animating to a child object and animate that object instead

digital crater
#

What do you mean? Sorry, only a few weeks into Unity dev, but decent at C#

leaden ice
#

Your object has a renderer of some kind, yes? That's the thing the animator is animating, yes?

#

e.g. a SpriteRenderer that is being animated by changing its Sprite

digital crater
#

So, I apply the Animator to the children?

rigid island
#

ah it was animator all along..yeesh

#

i forget it can overtake transform without Root Motion 🫣

leaden ice
digital crater
#

Ah ok

#

I’ll do that a little later

#

Thanks @rigid island and @leaden ice for you help

upper patrol
#

Hallo everyone, does anyone know this error:
InvalidOperationException: Failed to load XRReferenceImageLibrary 'ReferenceImageLibrary': library does not contain any ARCore data.???

modern creek
#

a quick google suggests file paths with spaces in their names might be the issue

digital crater
tawny mountain
#

Hello everyone.. I have a question real quick about nav mesh agents paths.. how does the nav mesh agent choose its path , is it always the shortest path? and if so how can I get the agent to select a diffrent path?

remote trout
#

Hey yo so I tried making a parallax scrolling effect in unity 2D for my game and there are two layers; Maze & Glitch_BG

I made a simple code for the Parallax Scrolling and it works, however there is these weird artifacts or something... I think it's easier to just show it [Check video]
In the sides, where like the empty/transparent part is, it for some reason just stays and is not working. It is meant to be working like in the transparent parts in the center-ish area.

Thanks :)

leaden ice
remote trout
#

No.. No I don't think so

leaden ice
remote trout
#

(sorry if I sent way too many photos im still learning)

steady valve
#

why is this happening, i can download pacakge but i cant import

#

and seems network is ok

olive mesa
steady valve
olive mesa
#

check the console

steady valve
#

something went wrong is the only error i get

somber nacelle
#

also check the !logs

tawny elkBOT
#
📝 Logs

Documentation
Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub
Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

olive mesa
#

yup

steady valve
#

console is clean

olive mesa
#

try again mayhaps see if anything pops up

#

if you're getting an error in the package manager you should get one in console

steady valve
#

restarted editor

#

btw editor version is 22.3.7f1

#

so i noticed there are some package error related

leaden ice
steady valve
#

strange, created a fresh new project and same thing happened

#

log says there is a memory leak?

olive mesa
steady valve
#

ik this is really confusing

#

editor doesnt give me a meaningful error

olive mesa
#

if it happens in a new project though, there's a good bit of confidence in assuming that it's nothing to do with your actual projects

steady valve
#

same thing in my actual project

#

and i even reinstalled everything

#

same error

olive mesa
#

I had an issue with the package manager myself but it was because I had a windows feature disabled and it broke it

steady valve
#

in my case, i can download package in package manager but i cant import it

olive mesa
#

odd

steady valve
#

sign let me try 2023 see if this still happen

steady valve
#

yup 2023 works fine

#

wth

somber nacelle
#

sounds like you should be submitting a bug report for the version that isn't working

steady valve
#

but what should i submit. as above shown, the only error is "something went wrong"

somber nacelle
#

!bug

tawny elkBOT
#

🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!

💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

olive mesa
#

submit the logs basically

steady valve
#

got it

olive mesa
#

unity has a bug reporter built in you should be able to just use that

#

you should know about it if you've ever had the damn thing crash on you

carmine prism
#

Any idea how to stop player from getting launched whenever it walks over an object? Is something wrong with my script?
Script:

private void MovePlayer()
{
    moveValues = playerControls.Move.ReadValue<Vector2>();
    if (isGrounded && moveValues == Vector2.zero) { EnableFriction(); }
    else { DisableFriction(); }


    
    float calcedMovementSpeed = walkSpeed;
    if (isSprinting && moveValues.x == 0 && moveValues.y > 0) { calcedMovementSpeed = sprintSpeed; } // SPRINT IF GOING FORWARD AND NOT GOING SIDEWAYS
    if (isCrouching) { calcedMovementSpeed *= crouchSpeedModifier; }

    Vector3 movement = (transform.right * moveValues.x) + (transform.forward * moveValues.y);
    movement *= calcedMovementSpeed;

    movement.y = rigidbody.velocity.y;

    rigidbody.velocity = movement;

}

https://streamable.com/gyq1xx

leaden ice
#

horizontal velocity becomes vertical velocity

steady valve
#

check your gravity setting

#

your player has an up velocity when player touch the sphere

carmine prism
carmine prism
steady valve
#

i noticed you use rigidbody for player, it has simulated physics which may result into unwanted behaviour use Kinematics instead

late lion
leaden ice
carmine prism
#

dont want my player to jump over rocks like that

#

ah, will probably do something that slows player down based on how much of a slope it's walking on

sleek stream
#

can anyone help me or give me a script for bounciness. like oncollisionenter add upward force?

#

cause physic material doesnt giuve enough bounce

somber nacelle
#

this isn't the place to get free code handouts. what specific part of that are you having trouble figuring out how to do?

sleek stream
#

i dont have a clue on code at all

somber nacelle
#

well if you don't know how to code, there are beginner c# courses pinned in #💻┃code-beginner to help you get started with learning

sleek stream
#

ok thanks

#

ok ive wrote the script below with help from a friend and it doesnt work. ive gave my player the script and a tag called OnTriggerEnter and my bouncy object a tag called BounceTrigger. when my player falls onto the bouncy object it does not bounce.https://hastebin.com/share/okitecebet.csharp

sleek stream
#

yes

#

ahould i debug?

knotty sun
#

So why does your code not contain any?

knotty sun
sleek stream
#

i dont think the collision is working. nothing appeared in the log

knotty sun
#

show latest code

#

screen shot is ok

crisp bronze
#

Has anyone here gotten VS Code's new Unity extension to work properly on Mac? I installed it and the required extensions along with the Unity package, and Intellisense is still failing to complete. I get this error:

[info] Project system initialization finished. 0 project(s) are loaded, and 37 failed to load.
glossy ledge
#

COULD USE SOME HELP!!!
When I use target API level 33, this doesn't generate a permission pop up... it does work on older API levels

knotty sun
#

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

glossy ledge
# knotty sun and also !code

This is the code that generates a permission pop up on Android:

void Awake()
{
instance = this;
DontDestroyOnLoad(instance);

    if (!RuntimeManager.IsInitialized()) { RuntimeManager.Init(); }

#if UNITY_ANDROID

    if (Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead))
    {
        Debug.Log("King of Crokinole has access to Gallery");
    }
    else
    {
        Permission.RequestUserPermission(Permission.ExternalStorageRead);

    }

    if (Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
    {
        Debug.Log("King of Crokinole has access to Camera");
    }
    else
    {
        Permission.RequestUserPermission(Permission.ExternalStorageWrite);

    }   

#endif

}

And it worked like a cham on API level 30 ...but not on 33

mild osprey
#

I'm having an issue where unity just doesn't allow me to disable vsync, i've tried QualitySetting.vSyncCount = 0 and force disabling it through my GPU settings but literally no matter what it will not disable

glossy ledge
#

It's very simple guys;
This code:

```Permission.RequestUserPermission(Permission.ExternalStorageWrite);

Generates a pop up on Android devices asking their permission to access storage (Gallery/Camera) ...this works fine when I create a build older than API Level 33...if I create a build on API level 33...the pop up doesn't come up.
glossy ledge
wide dock
#

Got a weird bug going on.
Whenever I enter and exit playtest mode my int field on my ScriptableObjects gets reset to 0.

[SerializeField] private int _ID;
public int ID => _ID;

public void SetID(int newID)
{
    Debug.Log("Setting new ID...");
    _ID = newID;
}

The only way to modify the ID is by the SetID method, it doesn't get called and yet the ID is being reset upon exiting playtest (the ID is not changed during it). Other fields stay as they were. Changing the name doesn't help.
And weirdly enough, if I click on my ScriptableObject file and keep it opened in the inspector, the ID doesn't get reset when exiting playmode.

Any idea what might be going on?

somber nacelle
#

do you perhaps have something calling SetID in OnDestroy?

leaden ice
wide dock
#

Another thing to note: if this scriptable object is referenced anywhere else it also doesn't lose it's ID

leaden ice
#

Are any instances of this thing created at runtime? (e.g. through Instantiate or ScriptableObject.CreateInstance?

lean sail
#

just one of the reasons to not use this for mutable data

wide dock
leaden ice
wide dock
# leaden ice show the code that does this? What triggers it?

Within OnPostprocessAllAssets if there was any change in the path containing these files, there is a call to my library which then loads all the files via Resources.LoadAll<>() and resets all the ID's using a ID generator which takes the file name as input

wide dock
#

Whenever I choose an enum, OnValidate() calls my library and caches the reference to that scriptable object

#

The only piece of code which set's the ID is this

missiles[i].SetID(UniqueIdGen.Generate(missileNames[i]));

missiles is the array created via the LoadAll call, missileNames is the array of the file names, so missile[i].name (with some changes along the way)

wide dock
lean sail
#

If it's something being changed in editor that's still a bit odd

wide dock
#

Yeah, I referenced all of them in the scene and now the ID doesn't reset, so I guess it's kinda a solution.
Still a bit weird

#

That's how it looks when it's not referenced anywhere

#

For now I'll just keep them referenced in the scene, I rarely add new ScriptableObjects like these ones (with an ID) so it won't bother me that much

delicate zinc
#

i've been having some inconsistent behaviour using Raycast, i have this node tool and i wrote a code to check if two nodes are in LOS, and if so, create a link between them

On video A, we see the correct behaviour, trying to put a node on the right side of the wall, the cylinder goes red and so does the ray to showcase that LOS is not possible.
https://i.gyazo.com/c39c488560bff80853fe230c0a85cba3.mp4

However, on video B, the LOS is somehow succeeding and not failing, despite the wall being between both nodes.
https://i.gyazo.com/8b229950f35b7690696b3eaa3624a78f.mp4

Does anyone have an idea on what could cause this weird collision behaviour? here's the raycast code i made
https://hastebin.com/share/jugodizexe.bash

pastel musk
#
{
    Vector4 result = default(Vector4);
    result.x = ((float)((int)instanceHolder % OBJECT_COLORMAP_WIDTH) + 0.5f) / (float)OBJECT_COLORMAP_WIDTH;
    result.y = ((float)((int)instanceHolder / OBJECT_COLORMAP_WIDTH) + 0.5f) / (float)OBJECT_COLORMAP_HEIGHT;
    result.z = 1f;
    result.w = 0f;
    return result;
}
#

what is the purpose of this function?

cosmic rain
hexed geode
#

I'm trying to make a system that allows my players to select an image on their computer to use as a skin in my game. This is my first time working with anything like this and I'm not very sure what went wrong. Actually selecting the image on my pc made it so that the font I was using, along with, somehow, basically my entire UI, became the image I chose. What did I do wrong?

#
public void SelectCustomSkin()
    {
        string path = EditorUtility.OpenFilePanel("Select image", "", "png");
        if (!string.IsNullOrEmpty(path))
        {
            var fileContent = File.ReadAllBytes(path);
            Texture2D customSkinTexture = Texture2D.whiteTexture;
            ImageConversion.LoadImage(customSkinTexture, fileContent);
            if (customSkinTexture.width != customSkinTexture.height)
            {
                EditorUtility.DisplayDialog("Select image", "The image has to be perfectly square.", "Ok");
                return;
            }
            Rect rect = new Rect(0, 0, customSkinTexture.width, customSkinTexture.height);
            SkinInfoHolder.instance.customSkin = Sprite.Create(customSkinTexture, rect, Vector2.zero, customSkinTexture.width); ;
            customSkinImage.sprite = SkinInfoHolder.instance.customSkin;
        }
    }

    public void UseCustomSkin()
    {
        PlayerPrefs.SetInt("skin", -1);
    }
cosmic rain
hexed geode
cosmic rain
hexed geode
cosmic rain
hexed geode
#

alright

#

it's very annoying to test because i have to fully restart unity everytime it happens because it doesn't reset otherwise

cosmic rain
hexed geode
#

no, the UI elements of unity itself still have that image, and every font still does as well

cosmic rain
hexed geode
#

unity itself becomes this image

#

look at the unity ui

cosmic rain
#

I don't see any issue with the unity ui...🤔

#

Anyways, I see it's assigned as a vertex color. Does it even take a texture normal? That's weird.

hexed geode
#

this is how it normally looks

cosmic rain
#

I mean, I see it affecting your in-game ui, but not the editor ui.

hexed geode
#

it changes the image to what i picked which shouldn't happen

red stratus
#

I have a fsm with only 3 states: wandering, chasing, attacking. It currently works as I'm expecting it to but I was curious. What if a target was to spawn directly in the attacking range. In my testing, it follows the happy path of chase->wonder->attack within fractions of a second. Is there a functional or performance reason to have the fsm change the state from wandering to attacking directly instead of going through the current positive path of wondering->chasing->attacking?

cosmic rain
cosmic rain
hexed geode
cosmic rain
#

Hmm

#

I see. That's still very weird, but good to know.

shell scarab
#

How do you access a 1D array as a 2D array again? I forgot the equation that's used.

#

is it i * width + j?

cosmic rain
#

You access 2d arrays with [I, j]. What you shared is accessing a 1d array as if it's a 2d array.

shell scarab
#

yea that's what I was asking sorry

cosmic rain
#

Then yes. Assuming i is rows and j is columns.

cosmic rain
#

For example, if transitioning between each of these states would play a certain sound, you'd hear a cacophony of sounds mixed together due to several states changing within several frames.

shell scarab
#

for example in a for loop would it be

for(int i = 0; i < width; i++)
```or
```cs
for(int i = 0; i <= width; i++)
earnest gyro
#

Bit field Enums and GameObject names

cosmic rain
#

It should be exclusive: < width.
Since width is the count of the elements in the row and arrays start from index 0.@shell scarab

shell scarab
#

👍 thanks

red stratus
shell scarab
#

Also just gonna ask this here rq, does TimeoutException make sense right here to you guys?

int GetNormalRoom(bool biasDirection) // true bias direction is max value, false is 0
{
  const int triesUntilAbort = 1000000;
  int x, y, c = 0;
  do 
  {
    x = axisBias ? randomGenerators.level.NextInt(0, floorSize.x) : biasDirection ? floorSize.x - 1 : 0;
    y = axisBias ? (biasDirection ? floorSize.y - 1 : 0) : randomGenerators.level.NextInt(0, floorSize.y);
    if (++c == triesUntilAbort)
      throw new System.TimeoutException("Took too many tries to find a valid room position.");
    } while (roomArray2D[x * floorSize.x + y] != RoomType.Normal);

  return x * floorSize.x + y;
}
somber nacelle
#

you could always just create your own exception. like a TooManyTriesException if you feel that TimeoutException doesn't convey what is actually happening

shell scarab
#

true. I was taught to almost never make exceptions and ig it just stuck with me.

west pelican
#

for some reason my i-frames iEnumerator isn't working

    private IEnumerator Invincibility()
    {
        invincible = true;
        Physics2D.IgnoreLayerCollision(8,9, true);

        for (int i = 0; i < numFlashes; i++)
        {
            rend.color = new Color(1, 0,0,0.5f);
            yield return new WaitForSeconds(iFramesDuration/(numFlashes*2));
            rend.color = Color.white;
            yield return new WaitForSeconds(iFramesDuration / (numFlashes * 2));
        }
        Physics2D.IgnoreLayerCollision(8, 9, false);
        invincible = false;

    }

i copied this code from my old project where i followed a tutorial
it worked perfectly there but doesnt work here

#

for some reason the renderer doesn't feel like working

#

i have the variable "rend" Serialized and i dragged in the Player's sprite renderer

leaden ice
#

Define "not working"?

west pelican
#

the sprite is supposed to flash between red and normal whenever the player gets hurt

#

but it doesnt do that

leaden ice
#

Is the code actually running?

#

Have you checked with logs?

west pelican
#

yes, because the i-frames themselves work

#

the actual invincibility works, but the visual doesn't