#💻┃code-beginner

1 messages · Page 728 of 1

silver fern
#

I think it's because the method is on the script component, not the object

hot wadi
#

No, it is not

naive pawn
hot wadi
#

Oh, right

naive pawn
shell sorrel
#

oh yeah you used the same name as the unity character controller

#

change the name of your's or use the fully qualified name for the unity one

#

private UnityEngine.CharacterController _controller;
would also need to change the get component line as well

silver fern
#

that's smart, I'll try that thanks

polar acorn
cosmic dagger
#

Can you post the constructor from one of the effects, like Burn? There's another idea you can use . . .

silver fern
naive pawn
west sonnet
#

When I instantiate an object, it's instantiates a clone of the gameobject. Is it possible to instantiate it so that it's an "original" version of the gameobject?

wintry quarry
#

var clone = Instantiate(original);

#

the original goes in the parameters

#

the thing you get is a clone

shell sorrel
#

sounds x y problem

#

the point of instantiate is making a clone of a object or creating a scene object from prefab

west sonnet
#

This is my code "Instantiate(weaponPickUpPrefabs[SelectedPrefab], transform.position + transform.forward, Quaternion.identity);", and you can see in the screenshot that the gameobject has Clone in parenthesis. I think the fact that it's a clone is messing up my script logic

#

Was wondering if there is a way around it before changing my script

brave robin
#

Oh, you want to rename the instantiated object so it doesn't have (Clone) in the name

wintry quarry
#

which is a bad idea

shell sorrel
#

your logic should be written in a way the name does not matter

west sonnet
#

No, it's not depending on the name

shell sorrel
#

so where and why is the name of it being used

west sonnet
#

Maybe I've misunderstood what is happening

wintry quarry
#

so you should explain what's actually happening

shell sorrel
#

the (Clone) part is just its name being changed

grand snow
grand snow
brave robin
#

There's no difference between an instantiated clone and the original saved asset, other than the original being an asset and not an object in the scene
Unless you're trying to modify some instance data on the clones and expecting it to propagate to the original, which won't happen and is a bad way of going about it anyways

wintry quarry
#

Should just really share the code, explain what it's supposed to do , and explain what's happening instead.

west sonnet
#

So I've realized I need the instantiated gameobject to have a reference to a prefab when it's instantiated

shell sorrel
#

i still think you are approaching something wrong

#

normally the prefab is just a template and just used for instantianteing

#

then you keep the returned reference from instantiate to do stuff with the new instance

brave robin
#

You can instead store the reference on a scriptable object. Its indirect, but avoids the issue you're running into

terse crescent
#

Yo

chilly elm
#

I’m new

#

What’s a good way to learn coding in unity

terse crescent
#

I'm having a bit of a weird problem... I'm running the game, but apparently the camera doesn't cover to screen size I set in the Project Settings

#

Which's 800x600

wintry quarry
#

Did you make a build, or you're running it in the editor? Or what?

terse crescent
#

I already figured there's this thing called size on the ortographic view mode, but I can't figure out how it works

wintry quarry
#

the Game window has a resolution picker

#

by default it's just whatever size the window is

terse crescent
#

Ok

#

So, now I need to figure out why my 64x64 sprite exits the screen when I set its X position to 800

#

My camera settings are probably not the way they are intended to be ig

#

I still don't know how it works

wintry quarry
#

so with size of 400 you will see 800 total units vertically

#

and the horizontal size will be based on your aspect ratio

#

so if you have a 2:1 aspect ratio - your horizontal size here is 1600 units

#

So the other questions are:

  • what is the position of the camera
  • what are the Z and Y positions you set the sprite object to? THose matter as well.
terse crescent
wintry quarry
#

the camera should be at z = -10

terse crescent
#

Reseted it then

#

What now?

wintry quarry
#

Now you should see the object.

If you can't, share screenshots of everything

#

positions of everything, inspectors, etc

terse crescent
#

It works now

#

But what the Z axis do anyway? I though that was a 2D editor 💀

random lodge
#

Read for a while about using a struct and this is probably obvious but need a nudge in the right direction. A little confused. I know the code works for instantiate other than this part.

#

Forgot this part int randomSpawn = Random.Range(0, spawnList.Length);

naive pawn
#

cameras only render what's in front of them, and "front" depends on the z axis

#

unity is a 3d engine with a lot of 2d tooling, so much so that it works as a 2d engine as well

naive pawn
#

a struct of just 1 member isn't.. super useful tbh. do you plan to expand this at all?

random lodge
#

Yea. The instantiate doesn't work with that line in there spawnList[randomSpawn].gameObject so I've screwed up somewhere.

terse crescent
#

Well

#

Thank you

random lodge
#

Done as many checks as I can but don't see where the problem is

terse crescent
#

-# geez, I can finally go study now

polar acorn
random lodge
#

From what I read it was better for later if extended

polar acorn
random lodge
#

No spawning or error

polar acorn
#

Are you sure that line is running

terse crescent
#

Bye

random lodge
#

Yeap, works if I replace that part and manually tell it which gameobject

cosmic dagger
# silver fern the constructor is ```CS public BurnEffect(DamageController damageController = n...

Sorry, I was AFK. There is another option with SOs. Instead of using an enum, you use a ScriptableObject enum (basically, an SO that acts as an enum). This helps because the SO will have its own method to create the effect, thus removing the switch altogether. Here's a short example

    [CreateAssetMenu(fileName = "NewEffect", menuName = "hb/Effect", order = 1)]
    public abstract class SO_Effect : ScriptableObject
    {
        public abstract Effect Create(EffectContext context);
    }

Then you create derived types for each effect, like public class SO_BurnEffect : SO_Effect that override the Create method.
Before, I mentioned creating a struct or class that holds all of the passed effect data. I'd still make that; it holds all the information for an effect

    [Serializable]
    public class EffectContext
    {
        public int Power;
        public float Duration;
        public int Frequency;

        public CharacterController2D CharacterController;
        public DamageController DamageController;
        public WeaponController WeaponController;
    }

This is the class I used for Effect since you pass all these fields in the method

    [Serializable]
    public class Effect
    {
        public int Power;
        public float Duration;
        public int Frequency;
    }

Now, in the EffectController, you can do this within the method . . .

        public Effect ApplyEffect(SO_Effect effectConfig, EffectContext context)
        {
            var effect = effectConfig.Create(context);
            activeEffects.Add(effect);
            OnEffectApplied?.Invoke(effect);
            
            return effect;
        }

The main difference, is you pass the SO instead of an enum . . .

polar acorn
random lodge
#

Should this actually print anything in the log if it's correct? Debug.Log("Object: " + spawnList[randomSpawn].gameObject);

polar acorn
#

If nothing prints from that log then that line is never running

#

If it's logging the value Object: then it means that the object in that slot is null

random lodge
#

ah ha, ok weird

#

I know how I broke that now

smoky urchin
#

Hello, I don't know if I'll find the help I need here, but I'll give it a try.

I'm modding the game 7DTD and trying to create a mod that equips a helmet armor modifier. (They're like upgrades.)

Is there any way to hide the mesh/model in C# using Unity references?

naive pawn
grand snow
#

if only the question was asked more generally, then we can point out you can disable the renderer component to stop something rendering (or remove it)

smoky urchin
#

What if I continue speaking in general terms? xD

polar acorn
#

There will probably come a point where you'll get an answer that can't be implemented because of the restrictions you're working under, and that's the point support will likely end since it's highly unlikely anyone here knows of the specific limitations of this framework

edgy prism
#

Hello, Im working on a function that scrolls to a position in my scrollview based on a given index 1-29, it was working ok where the height of my UI elements was 200, then I added a title so added an extra 400px of padding to my scroll view content now it is always displaying -400px from the desired Y position and I cant for the life of me figure out how to account for the padding without messing up the maths any help is greatly appreciated!

public void ScrollToLevel(int levelIndex)
{
    levelIndex = Mathf.Clamp(levelIndex, 0, totalLevels - 1);

    float targetY = (levelIndex * levelHeight) + (levelHeight * 0.5f);

    float centeredY = targetY - (viewportHeight * 0.5f);

    float scrollableHeight = content.rect.height - viewportHeight;

    float normalizedY = Mathf.Clamp01(centeredY / scrollableHeight);

    scrollRect.DONormalizedPos(new Vector2(0, normalizedY), 0.3f)
        .SetEase(Ease.OutCubic);
}
fickle yacht
#

Is the correct channel to ask for help with a Unity Learn lesson?

grand snow
edgy prism
radiant voidBOT
# naive pawn !ask

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.

-# For more posting guidelines, go to #🌱┃start-here

grand snow
edgy prism
grand snow
languid pagoda
#

How can I make it so the gauge cluster lights up like on a real car?

edgy prism
viral pasture
#

Hey, I'm probably missing something but why are my colliders not touching?

#

The physics works fine, the player stops and all but is floating just above the ground.

languid pagoda
edgy prism
# grand snow The point of that was to reduce the "valid scroll area" from 0-1 to the area whe...

I know that if my content height is 6200 and 400 of that is padding then my "valid scroll area" is 5800 but if I try and adjust the scrollable height variable by accounting for that things go sideways quick

float paddingAdjusted = content.rect.height - 400f;

float scrollableHeight = paddingAdjusted - viewportHeight;

float normalizedY = Mathf.Clamp01(centeredY / scrollableHeight);

scrollRect.DONormalizedPos(new Vector2(0, normalizedY), 0.3f)
    .SetEase(Ease.OutCubic);
viral pasture
#

@languid pagoda I'm editing them but in my head the colliders should touch no?

languid pagoda
#

on the collider component there is an edit collider button is there not?

viral pasture
#

@languid pagoda there is but the collider would be smaller than the sprite

#

I'm just wondering why the colliders are not touching, I can fix it easily but just wondering why

languid pagoda
#

there could be several reasons as to why

#

your screenshot really tells us nothing

rocky canyon
viral pasture
#

@languid pagoda No problem, just tell me what you wan't to see, I'm just using a normal RigidBody2D, haven't configured anything in the project settings.

#

this is probably not the right channel either, tell me off if you guys want me to move somewhere else

languid pagoda
grand snow
#

So technically the area we can focus on is -viewport height/width

#

And elements in those un centerable zones will use 0 or 1.

rocky canyon
languid pagoda
rocky canyon
#

go into blender and add a new material / assign it to those faces

languid pagoda
#

what is the name of the shader to use for this tho?

viral pasture
grizzled dove
#

my unity installing 30 min, is it a bug or something?

rocky canyon
viral pasture
#

seems to be some kind of offset 🤔

zenith wren
#

I'm currently trying to make my own editor window but for some reason I don't have the "tools" option on my editor. I'm using 6.2 and the image is from someone using 6.0
This is from a tutorial:

languid pagoda
#

obviously thats up wayy to bright but im shocked how easy that was

polar acorn
grand snow
#

Most people use tools

silver fern
cosmic dagger
low copper
#

Quick question...when running a singleton via a public class extending Monobehaviour. Is it standard practice to call it "Instance" or "instance"?(capitalized or not)

public static ExampleClass instance;

based on what I've learnt it seems like variables are normally lowercase but I've looked a bunch of examples and it seems many people do it with capitals.

shell sorrel
#

style stuff is up to preference, and the style used in unity stuff differs from other C# so you will often see a mix

low copper
#

I assume its more about being consistent in the project?

shell sorrel
#

yup

buoyant wind
#

my guy not sliding

#

or even falling

silver fern
#

did you write code to make him fall

rain solar
#

The material point method (MPM) is a numerical technique used to simulate the behavior of solids, liquids, gases, and any other continuum material. Especially, it is a robust spatial discretization method for simulating multi-phase (solid-fluid-gas) interactions. In the MPM, a continuum body is described by a number of small Lagrangian elements ...

silver fern
rain solar
#

its generalized beyond recognition in the article

silver fern
rich adder
rain solar
silver fern
rain solar
buoyant wind
#

nevermind i figured out something

twin pivot
#

how do i reference the animation the StateMachineBehaviour script is on? nvm just realized it inherits from SOs

polar acorn
eager elm
#

Trying to run a Coroutine from a non-MonoBehaviour, getting a reference to any MonoBehaviour by passing it in the Constructor or using Singleton, or is there a better solution? I want X to happen 3 times every 0.1 seconds.

shell sorrel
#

it needs a object to run on, so yeah you will need to pass that along

timber tide
#

Singleton manager that executes the routines I've done before and it works pretty well

eager crow
#

Can anyone help figure why this is giving me a compiler issue?

polar acorn
eager crow
#

does c# not support free functions?

random lodge
#

Alright someone telling why I am being dumb 😝 The error is object reference not set to an instance of an object. My brain hurts.

shell sorrel
polar acorn
north kiln
shell sorrel
teal viper
random lodge
shell sorrel
#

@random lodge you likly forget to assign something in the inspector

north kiln
polar acorn
slender nymph
random lodge
#

Alright I'll check that again

north kiln
teal viper
slender nymph
#

That's not quite the same thing though because those are still local functions since they get compiled into the Main method

shell sorrel
#

the global scope methods are all just sugar, the cil is more or less the same as methods in a static class

teal viper
timber tide
#

namespace methods would be nice

#

not that making a utility class inside one is that big of a problem

teal viper
shell sorrel
snow patrol
#

what would the best channel be to get some help figuring out why my UI toolkit inspector is read only?

#

for reference this is what I mean

#

I'm trying to modify scriptable objects from my custom window

vague rivet
#

Ok. How do i use the old Input system while also using the new one? I plan to use the new one for general controls and such, but fur a debug hud, I just want to simply press F1 to toggle it. Do i really have to use the new Input System package for it?

snow patrol
#

Project Settings -> Player -> Other Settings -> Active Input Handling

#

set that to both

terse crescent
#

I'd like to know why the heck nothing is getting printed:

#

The second image is how it is on both objects

polar acorn
polar acorn
terse crescent
#

I'll screenshot the rigibody2D one

#

Which's also the same

polar acorn
#

The full inspector of both objects would let me check everything at once

terse crescent
#

How can I easily show it?

#

Like, screenshot it easily

polar acorn
#

Yes

#

Instead of cropping it

#

Just send the whole thing

teal viper
#

Just screenshot it easily

terse crescent
#

It won't fit the whole screen :/

polar acorn
#

You can hide large blocks of un-editable data like the rigidbody info

terse crescent
#

So, this is the player

#

This is the other one

polar acorn
#

Which script has the OnTriggerEnter2D?

terse crescent
#

PlayerCollider

#

On player

#

public class PlayerCollider : MonoBehaviour
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log("Test");
    }
}
polar acorn
#

And how are you moving the player?

terse crescent
#
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;

public class Player : MonoBehaviour
{
    public InputAction playerControls;
    public Rigidbody2D rb;

    public float MoveSpeed = 640.0f;
    public Vector2 MoveDirection = Vector2.zero;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        transform.position = new Vector2(0, -225);
    }

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

        MoveDirection = playerControls.ReadValue<Vector2>();

    }

    private void FixedUpdate()
    {

        rb.linearVelocity = new Vector2(MoveDirection.x * MoveSpeed, 0);

    }

    private void OnEnable()
    {
        playerControls.Enable();
    }

    private void OnDisable()
    {
        playerControls.Disable();
    }

}
    ```
polar acorn
terse crescent
#

wdym?

rich adder
#

rb2d is weird man it still has velocity w kinematic

polar acorn
rich adder
#

ohh nice

terse crescent
#

So, what's the fix?
-# WHY CAN'T I TYPE SO?

polar acorn
#

At least one of the rigidbodies needs to be dynamic

#

Probably the one that moves

terse crescent
#

And dynamic means it has physics, right?

#

Anyway, both of them move

rich adder
terse crescent
#

So... -# pls don't delete

#

I set one of them to Dynamic

#

Set the gravity to 0 just so it isn't affected by, yk, gravity

#

But it still prints nothing

rich adder
abstract copper
#

https://pastebin.com/yAaybB58
Any reason as to why my enemies stop spawning after like 5 spawn? something around that. I made sure to check if game state is being sate to over but its not its always playing.

terse crescent
#

I still can't figure out the problem

#

Wait, no

#

The solution, mb

polar acorn
terse crescent
polar acorn
#

You appear to have a log that is hidden

terse crescent
#

Hm, let me see

#

💀💀💀

#

Why couldn't it appear by default?

#

lmfao

#

Thank you

rugged beacon
#

im not quite sure on the usage of [SerializeReference], i read it allow drag drop subclasses? but i dont seeing this with my script? whats the usage for this

using System;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    [SerializeReference]
    private EnemyBehavior behavior;

    [ContextMenu("Perform Attack")]
    public void PerformAttack()
    {
        behavior?.Execute(gameObject);
    }
}

[Serializable]
public abstract class EnemyBehavior
{
    public abstract void Execute(GameObject enemy);
}

[Serializable]
public class MeleeAttack : EnemyBehavior
{
    public float damage = 10f;

    public override void Execute(GameObject enemy)
    {
        Debug.Log($"Melee attack deals {damage} damage!");
    }
}

[Serializable]
public class RangedAttack : EnemyBehavior
{
    public float projectileSpeed = 5f;

    public override void Execute(GameObject enemy)
    {
        Debug.Log($"Ranged attack shoots at speed {projectileSpeed}!");
    }
}
polar acorn
terse crescent
shell sorrel
#

since otherwise it does not know how to create a instance of each of the possible types or really your intent

rugged beacon
#

im required to do second half to use attribute? or whats its originally use for ?

#

i think i maybe see it, i can pre populate the reference with code and it show up on the inspector

random lodge
#

Wait, how does that work? The { } around the variable. You need the $ or that always works? Looks better.

rich adder
random lodge
#

😛

#

Things like that happen quite a few times a day at this point.

onyx patrol
#

Hello everyone, I am making a strategy game and I will be making region sprites you can conquer

#

But I want to make a border around each of them that changes color depending on what faction owns it

#

Like this for example, how could I make a border around this and be able to change its color through script

#

Is it something I have to do with photoshop itself or is there a tool which makes borders in Unity

#

Sorry if this is not the right channel to post this question, didn't really know where it could go

random lodge
#

Wonder if there's a "stroke" option in Unity like in Photoshop.

#

No idea how you would if you can though.

frosty hound
#

You need to create a custom sprite shader. It's a common need and there are sprite shader assets on the store that you can get.

#

Alternatively you make the outline a separate sprite that you layer with the main one, and change the colour of it in code.

random lodge
#

Second option seems relatively easy.

#

Though the first has advantages lol

teal viper
#

Chat gpt actually seems to work surprisingly well. At least way better than whatever unity uses in their Ai tools.

onyx patrol
#

I am unfamiliar with sprite shaders, how do they work?

teal viper
onyx patrol
#

Thank you everyone, I will look more into this

twin pivot
#
    public Animation myAnimation;
    void Start()
    {
        myAnimation = gameObject.GetComponent<Animation>();
    }
    void Update()
    {
        if(myAnimation.isPlaying)
        {
            Debug.Log("true");
        }
    }
#

is there a way to do this but using the animator instead?

twin pivot
#

yea just realized I was looking at the animation trying to find info on animators

silk night
obsidian grove
#

is there a way to suppress certain editor warnings?
I don't believe #pragma disable works with this since there is no warning code (CS####)

silk night
#

And that is not a compiler issue, as such you cannot suppress them with compiler directives 😄

obsidian grove
#

I have a ton of prefabs with multiple box colliders in them, technically I am being a bit lazy by just flipping them instead of making new prefabs but that would take hours

floral garden
#

You are making a 2d game?

obsidian grove
#

no, 3d

floral garden
#

Ok UnityChanFinished

loud salmon
#

(Repost as previous wasn't so clear) (TLDR: Mesh Stretches when being rotated on any axes)

So basically when using soft-body on a non-cubical object, the mesh vertices (appear to) try and always face the same direction when rotating it using Unity's transform rotation or the node grabber. My suspicion is either: The DQS implementation is wrong, something with XPBD calculation itself or The fact that the soft-body's transform doesn't update to show positions or rotation changes. I will literally be so thankful if you (somehow) manage to find a fix for this stubborn issue!

What I've Tried:

-Rewriting the scripts

-Renaming all variables properly

-Used different Mapping methods

-Debugging

-Using the Help of AI

Video: https://drive.google.com/file/d/1bYL7JE0pAfpqv22NMV_LUYRMb6ZSW8Sx/view?usp=drive_link

Repo: https://github.com/Saviourcoder/DynamicEngine3D

Car model and asset files: https://drive.google.com/drive/folders/17g5UXHD4BRJEpR-XJGDc6Bypc91RYfKC?usp=sharing

GitHub

Open-source Soft-Body Physics Engine for Unity3D. Contribute to Saviourcoder/DynamicEngine3D development by creating an account on GitHub.

#

wait is this the correct place to post this?

keen dew
#

Post either here or code-general but not both

analog pendant
#

I'm having issue, whenever I save my script , it takes time in compiling and all, any way to lessen up the time

midnight plover
teal viper
silver fern
#

much better than having to wait for the refresh every time I tab away and back to double check something

lunar coral
#
private void Update()
{
    // check for sight and attack range
    playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
    playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);

    if (!playerInSightRange && !playerInAttackRange)
    {
        Patroling();
        animator.SetBool("isWalking", true);
        animator.SetBool("isRunning", false);
        animator.SetBool("isShooting", false);
    }

    if (playerInSightRange && !playerInAttackRange)
    {
        ChasePlayer();
        animator.SetBool("isWalking", false);
        animator.SetBool("isRunning", true);
        animator.SetBool("isShooting", false);
    }

    if (playerInSightRange && playerInAttackRange)
    {
        AttackPlayer();
        animator.SetBool("isWalking", false);
        animator.SetBool("isRunning", false);
        animator.SetBool("isShooting", true);
    }
}
wintry quarry
#

Look up the state machine pattern. At the very least use else ifs.

lavish rose
# lunar coral ```csharp private void Update() { // check for sight and attack range pl...

problem is almost definitely inside your Patroling() function. my guess is you set a destination once and the bot just stops when it gets there. inside Patroling(), you need to check if the agent is close to its current destination (using something like agent.remainingDistance < 0.5f) and if you're not sure which state is active put a Debug.Log("Patrolling") in that first if statement to see if it's even being called

lunar coral
wintry quarry
#

I wouldn't have written it if I didn't think it

mighty peak
#

If i need make a ui text as integer or real number to increase it with variable should i make it in code or in unity?

lunar coral
# lavish rose problem is almost definitely inside your Patroling() function. my guess is you s...
private void Patroling()
{
    if (!walkPointSet) SearchWalkPoint();

    if (walkPointSet)
        agent.SetDestination(walkPoint);

    Vector3 distanceToWalkPoint = transform.position - walkPoint;

    // walkpoint reached
    if (distanceToWalkPoint.magnitude < 1f)
        walkPointSet = false;
}

private void SearchWalkPoint()
{
    // calculate random point in range
    float randomZ = UnityEngine.Random.Range(-walkPointRange, walkPointRange);
    float randomX = UnityEngine.Random.Range(-walkPointRange, walkPointRange);
    walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);

    if (Physics.Raycast(walkPoint, -transform.up, 2f, whatIsGround)) 
        walkPointSet = true;
}
wintry quarry
lunar coral
lunar coral
mighty peak
lunar coral
#

which should then find another one

wintry quarry
#

Which part?

mighty peak
wintry quarry
#

It is going to require both code and objects designed in the editor

#

There are code parts and editor parts. You need both

lavish rose
mighty peak
#

Couse now its just text

wintry quarry
mighty peak
#

Should i make it number or it will be in code directly?

wintry quarry
#

I'm honestly not really sure what question you're asking

wintry quarry
lunar coral
mighty peak
wintry quarry
mighty peak
#

Like if i make int var and make the Text in it then +1 to this var

#

Text will be 1 to 2 maybe?

wintry quarry
#

What do you mean by "make the text in it"?

mighty peak
wintry quarry
#

Pseudocode:

myNumber += 1;
myText.text = $"Health: {myNumber}";```
mighty peak
#

Huh

wintry quarry
#

Just look at my example

#

It should be that way

rocky canyon
#

if it were a string u would convert to int to add

        string numberString = "42";  // number as text
        int number = int.Parse(numberString);```
#

but u wouldnt want to use strings there

wintry quarry
#

String parsing is definitely not the way here

mighty peak
rocky canyon
#

thats what this is..

wintry quarry
rocky canyon
#

its the TextMeshPro's text field

rocky canyon
#
    private void UpdateHealthUI()
    {
        healthText.text = currentHealth.ToString();
        healthText.text = $"{currentHealth}";
    }```
both would output `currentHealth` as text
nimble apex
#

string interpolation, one of the best invention ever

rocky canyon
#

i agree

mighty peak
eager elm
# mighty peak Or?

you don't link it with a variable. When the variable changes you need to update the text with myTextField.text = someVariable;

grand snow
#

ugui cannot do this
UI toolkit has this functionality though

mighty peak
mighty peak
rocky canyon
#

i'd usually use a UIManager that already has the references to all the text elements i need

#

tell it to Update it (when it changes)... uiManager.UpdateSoAndSoText();

#

alot easier to find something like that (or even use a singleton) than it is to grab every element individually.. if i need to scoop it at runtime

#

that way u dont even need a Tag to get it

grand snow
mighty peak
rocky canyon
#

you assign that in another script.. already

#

like i just said.. something would alrady be referencing all the TMP elements that u need

mighty peak
#

So add Same script in both of them?

rocky canyon
#

both scripts could call the same script

#

that way u could tell the UI Manager (the brains of the UI) which could hold all ur UI stuff

#

and the UIManager does the updating (with the text reference it already has) b/c u would assign that in the inspector

mighty peak
#

Ok but how it will know which text im want

rocky canyon
#

you use different variables.. lol 🤔

#

one for each?

#

or different Methods..

mighty peak
#

Yes ok

rocky canyon
#
public class UIManager : MonoBehaviour
{
    public TextMeshProUGUI coinsText;
    public TextMeshProUGUI healthText;

    private int coins;
    private int health;

    // Called by other scripts
    public void SetCoins(int amount)
    {
        coins = amount;
        coinsText.text = $"Coins: {coins}";
    }

    public void SetHealth(int amount)
    {
        health = amount;
        healthText.text = $"HP: {health}";
    }
}```
#

think of it like that ^

mighty peak
#

Then should i call text which i want to new var

rocky canyon
#

hey, i have all the references i need to change anything in the ui
i'll just wait for someone to call one of my methods

#
uiManager.SetCoins(newCoinAmount);
uiManager.SetHealth(newHealthAmount);```
#

that way ^ u only need to get (1) script for any UI changes u need to do

#

u dont want to be having to "search" and then assign all ur Text elements at runtime
its not very scaleable..

mighty peak
#

So I don't feel like my mind is frozen

#

Now lets say my text in unity is scoretext

#

And i make var with score text for it

#

Then make other int to make it +1

#

Right?

#

Thats what i know to make code know which text i need

rocky canyon
#

you do whatever u need to do to calculate the score..
then you use .text of the textmesh element to change the text
you can use anything u want (but for this case you'd use ur score variable u calculated)

#

1 variable for the score
1 variable for the text

mighty peak
#

Add same tag or something?

#

Like var score = "score tag"

rocky canyon
#

bro.. you'd just drag and drop the fkn text element into a variable

midnight plover
#

!learn

radiant voidBOT
rocky canyon
midnight plover
#

You really should go through unity basics from what I assume reading your questions

mighty peak
mighty peak
#

Oh

#

Wait

rocky canyon
#

u can really just assign it

mighty peak
rocky canyon
mighty peak
#

I should click yes right?🙂

eager elm
rocky canyon
shell sorrel
polar acorn
rocky canyon
#

he threw out the instructional manual

#

thats why

mighty peak
#

Just click attach to unity

shell sorrel
#

the editor recompiles when it sees changes

polar acorn
midnight plover
#

Please, I beg you go through the beginner tutorials on Unity learn

shell sorrel
#

without taking some time to understand the basics you are going to have a bad time and waste much more time in the long run

mighty peak
#

And no errors now

polar acorn
#

You should be seeing compile errors highlighted in real time as you make them without attempting to attach a debugger

mighty peak
mighty peak
polar acorn
mighty peak
polar acorn
# mighty peak No

How about showing a screenshot (not a cell phone picture) of your unity console

mighty peak
#

In unity yes but i think its not from code syntax just null from loop

#

When i run game

eager elm
rocky canyon
#

👏 gottem!

mighty peak
#

I cant find text when i click in it🙂

shell sorrel
#

drag in your text object

mighty peak
#

And cant drag it because its selected when i click on it

polar acorn
#

Click on object with variable.
Drag in text object

#

You don't need to select the text object

mighty peak
#

Why can't i send screenshot from pc🙂

rocky canyon
#

you can..

mighty peak
mighty peak
#

Like that?

#

Servers system

rocky canyon
#

people are gonna stop helping or moderation will step in if u keep sending blurry photos
but you now need to fix that MissingReferenceException

mighty peak
#

Oh wait

rocky canyon
#

read the error..

grand snow
#

2004 camera vibes

mighty peak
#

I understand him wrong

grand snow
#

how do you expect people to help if you cant share things CLEARLY

rocky canyon
#

my amazon fire from 2018 takes better pictures

mighty peak
rocky canyon
#

yea thats the entire problem

#

stop taking phone pictures at all

mighty peak
#

Don't know how should i add it to var😂

#

Cant drag it out of hierarchy

rocky canyon
#

why not?

mighty peak
#

🤷

#

Maybe i do something wrong

#

But it's doesn't get out

earnest wind
#

why do you go back to using camera

earnest wind
midnight plover
#

😄

mighty peak
earnest wind
earnest wind
#

isnt that a TMP tho?

mighty peak
#

Yes

earnest wind
#

click on this and show me inspector

#

and then show me the code

#

no, unity is not buggy, something is just wrong..

midnight plover
#

I am done even reading this chat 😄 You seem to be fully aware to ignore the fact, that you are missing the most basic concepts of Unity entirely. People will waste their time helping you fighting through the most simple tasks and you wont learn anything...

mighty peak
#

Here its

rocky canyon
rocky canyon
#

if it doesn't allow u drag it into the slot then that means the Type of component ur trying to assign isn't on that gameobject

mighty peak
shell sorrel
#

learn the basics your are just wasting your time and others

rocky canyon
#

ur ignore ppl w/ valuable information

mighty peak
stone scroll
#

i download this demo but it say no camera what i should do to fix?

rocky canyon
#

you know Save next?
then tab over to unity , (give it time to recompile)
and if its successful u should have a variable in the scripts/ component

rocky canyon
#

or its spawned in later or with a scene change

#

u can disable the warning by right clicking the Game tab

#

or add a camera if u want ¯_(ツ)_/¯

mighty peak
#

full screen if he need it

rocky canyon
#

Thank the Lord! 🙏 finally not a phone selfie

mighty peak
rocky canyon
#

show the inspector of the GameObject ur trying to drag into that slot

mighty peak
#

Failed

rocky canyon
#

and when you get around to it you should click/dblclick this error and see where its coming from

mighty peak
#

But its above

rocky canyon
#

b/c it is something you have to fix eventually

rocky canyon
#

thats not a picture of the inspector

mighty peak
mighty peak
rocky canyon
#

but after that code runs the script breaks.. nothing else will run

mighty peak
#

Here its

earnest wind
#

show me the code

#

now

rocky canyon
#

^ full script

#

🥽 almost there

mighty peak
#

3 scripts?

rocky canyon
#

the one w/ the reference ur trying to drag in

earnest wind
rocky canyon
#

lol.. funny

earnest wind
#

😭

mighty peak
#
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UI;
public class get_coin : MonoBehaviour 
{
public Rigidbody2D nrb;
    public TextMeshPro score;
    private int scoreValue = 0;
    void start () {

}

void Update() 
{
  nrb.velocity = Vector2.up * 300 * Time.deltaTime;
}

void OnTriggetExit2D(Collider2D other) 

  {   
    if (gameObject.transform.position.y > 7)

    if(other.gameObject.tag == "player")
    {
    Destroy(gameObject);
                
                scoreValue += 0;
                score.text = score.ToString();
            }

  }

}
rocky canyon
earnest wind
#

its not TextMeshPro

#

its TMP_Text

rocky canyon
#

^ either that or TextMeshPro_GUI some nonsense

mighty peak
#

its not a shortname?

earnest wind
earnest wind
mighty peak
earnest wind
#

also holy pls format your code or smth 😭

mighty peak
#

In unity i was added tmp

earnest wind
#

its messed up bro

mighty peak
#

I hate that failed

earnest wind
#

bro, just change TextMeshPro to TMP_Text

#

whats so hard about that

#

nothing failed, you just made a typo with the variable type

hexed terrace
#

TMP_Text is the base class for TextMeshProUGUI and TextMeshPro. It's better to use TMP_Text but the UGUI one will work in this case aswell.

rocky canyon
rocky canyon
rocky canyon
#

ignore that...

public TMP_Text scoreText;

and move along w/ ur day

stone scroll
#

has anyone else downloaded the official Spaceship demo? I’m getting errors in SelectionHistoryWindow.cs (like CS1010: Newline in constant) even after trying some fixes. Did anyone else encounter the same issues?

earnest wind
earnest wind
hexed terrace
mighty peak
#

Added

rocky canyon
# stone scroll has anyone else downloaded the official Spaceship demo? I’m getting errors in Se...

no idea.. in situations like that where im trying to revive an outdated repo
i'll usually go in surgically and find the errors and ``// comment them out`
i'll then re-attempt to compile/run it... and rinse and repeat and even temporarily remove / rename scripts if
the whole thing is bugging.. and then u need to go thru the solution and remove any references to that script.. b/c that would cause it error out.. (sometimes i'll comment them out as well)

stone scroll
#

ok thank u

rocky canyon
#

sometimes its helpful.. sometimes its not.. usually u can get away with it running (albiet a few features might not respond)

mighty peak
rocky canyon
mighty peak
#

It is not convenient every time I choose what I want from screen movement, element movement, selection, etc.

rocky canyon
#

you've confused tf outta me ngl

mighty peak
mighty peak
#

I must select everything first and change it to what i want

hexed terrace
#

Are you asking if there is a quick way to rename something?

mighty peak
#

quick way for those

#

with mouse

hexed terrace
#

QWERT will swap between them

mighty peak
hexed terrace
#

... keys on your keyboard.

real ferry
#

idk if this is the right channel, but how ressource expensive is it when i shoot 3 raycats in an FixedUpdate() function?

#

and also do some rotations

shell sorrel
#

raycasts are not very expensive

real ferry
#

okayy

shell sorrel
#

3 in a frame update or a fixed update is no big deal

real ferry
#

good to know

#

how expensive is a transform.Rotate() since i am calling that also

#

but i guess no big deal either

shell sorrel
#

just make things work first

#

only worry about performance if it shows its a real issue

#

if that happens you have tools like the profiler to debug why

real ferry
#

alright good to know, thank u

shell sorrel
#

but yeah a rotate is pretty cheap as well, though try to not rotate the same objects many times on the same frame.

#

which should be easily avoidable by just figuring out the final rotation first

real ferry
#

well i am aiming for a continous rotation tbh

shell sorrel
#

that does not require multiple rotates on the same frame though that is just 1 per frame

real ferry
#
void FixedUpdate() {
    float rotateDirection = rotateRight ? 1f : -1f;
    transform.Rotate(0f, rotateDirection * rotationSpeed * Time.deltaTime, 0f);
}
#

this is what i did

shell sorrel
#

yeah totally fine

real ferry
#

ahh okay

shell sorrel
#

though why use fixed update

#

i see no physics involved in that

real ferry
#

whats the diff between fixed and normal idk really?

#

oh okay

shell sorrel
#

fixed update is really only needed for physcis stuff

#

otherwise Update is the better choice

real ferry
#

so a raycast is no physics too right

#

ahh i see

shell sorrel
#

yeah can raycast fine in Update, stuff like moving a rigidbody should be fixed update

#

90% of other thigns are regular Update

real ferry
#

okk that makes sense

mighty peak
#

!learn

radiant voidBOT
real ferry
#

thx for answering so fast

real ferry
rocky canyon
#

not sure u can be telling ppl to use something u seem to be actively ignoring

real ferry
#

you mean me?

mighty peak
real ferry
#

oh ok

mighty peak
#

Oh ok

silver fern
#

error on the learn site?

mighty peak
silver fern
#

odd, its working for me

naive pawn
#

that's not much info to go off of

#

you're gonna need to give more info if you want help

mighty peak
polar acorn
#

Did you remember to open your eyes

mighty peak
polar acorn
#

Well if there isn't one that's a good explanation for why you cannot see it

mighty peak
#

Box collider should make rigid body stand in it right?

naive pawn
#

what do you mean by "stop in"?

mighty peak
nimble apex
#

you can chain boolean and assignment right?

A = B = <boolean>```
polar acorn
nimble apex
#
    public void UpdateStatus(bool isActive)
    {
        col.enabled = isActive && isActivated;
        renderer.enabled = isActive && isActivated;
        
        col.enabled = renderer.enabled = isActive && isActivated;
    }```
wintry quarry
nimble apex
#

ok ty 👍

wintry quarry
#

bool x = a & b; is no different from bool x = a = b; grammatically.

nimble apex
#

good to hear i can finish it within one line lol

wintry quarry
#

I meanI would probably just make a property

#
bool _active;
bool active {
  get => _active;
  set {
    _active = col.enabled = renderer.enabled = value;
  }
}```
#

hmm guess you could use the chain assignment in the property too hehe

nimble apex
#

i would need to replan the isActivated in this case

#

done , i removed isActivated and can now make it to property 👍

mighty peak
heavy wing
#

Hi!
Can someone DM me who knows ML-Agents and can help me out?

rich adder
mighty peak
silver fern
mighty peak
#
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor.EventSystems;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class get_coin : MonoBehaviour 
{
public Rigidbody2D nrb;
    public TMP_Text score;
    private int scoreValue = 0;
    void start () {

}

void Update() 
{
 /* nrb.velocity = Vector2.up * 300 * Time.deltaTime;
*/
}

void OnTriggetExit2D(Collider2D other) 

  {
        if (gameObject.transform.position.y > 7) 
        {
            Destroy(gameObject);
        }



    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "coin")
        {
            Debug.Log("Coin collected! "+ scoreValue);
            scoreValue += 1;
            score.text = scoreValue.ToString();
            Destroy(gameObject);
        }
    }
}

silver fern
#

you misspelled trigger

mighty peak
wintry quarry
#

spell Trigger correctly...

mighty peak
wintry quarry
# mighty peak where?

why don;t you look at your code until you see where it's not spelled correctly. There's not that much.

frosty hound
#

Consider the fact you've used the word Trigger twice in that code, you should be able to spot it.

#

Furthermore, your !ide should be configured, it would be underlining it red.

#

!ide

radiant voidBOT
wintry quarry
wintry quarry
frosty hound
#

You're right ...

#

Configure it anyway if it's not

naive pawn
#

if the ide were configured the method would be marked unused

frosty hound
mighty peak
#

bro its from suggesion

naive pawn
#

and?

#

one of them is still spelt wrong

#

stop deflecting and start fixing things

mighty peak
#

and doesnt work

frosty hound
#

Niether of those sentences actually answers the question posed?

mighty peak
#

i think you didnt got my quistion

polar acorn
polar acorn
mighty peak
silver fern
polar acorn
mighty peak
#

Also i tried change tag to player but same

polar acorn
mighty peak
#

Be trigger

silver fern
#

did you save the file and refresh in unity too

mighty peak
#
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor.EventSystems;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class get_coin : MonoBehaviour 
{
public Rigidbody2D nrb;
    public TMP_Text score;
    private int scoreValue = 0;
    void start () {

}

void Update() 
{
 /* nrb.velocity = Vector2.up * 300 * Time.deltaTime;
*/
}

void OnTriggerExit2D(Collider2D other) 

  {
        if (gameObject.transform.position.y > 7) 
        {
            Destroy(gameObject);
        }



    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "coin")
        {
            Debug.Log("Coin collected! "+ scoreValue);
            scoreValue += 1;
            score.text = scoreValue.ToString();
            Destroy(gameObject);
        }
    }
}
mighty peak
#

I will take Break for houratwhatcost

silver fern
#

good idea

polar acorn
#

The three commandments of OnTriggerEnter2D:

  1. Thou Shalt have a 2D Collider on both objects
  2. Thou Shalt tick isTrigger on at least one of them
  3. Thou Shalt be moving a Rigidbody2D on at least one of them
#

Also,

#

!code

radiant voidBOT
random lodge
#

Would Vector3.Reflect be the right choice if I want to "bump" an asteroid off course with another object in 2D?

wintry quarry
#

Reflect will give you the bounce of a pool ball on the wall of the pool table, or the bounce of a ray of light off a mirror

#

It's possible you want some other kind of behavior. For example in "brick breaker" type games the ball bounces off the paddle at a different angle depending on which part of the paddle it hits.

silver fern
#

also I don't think it works if the asteroid isn't moving

random lodge
#

Yea the angle would be nice

wintry quarry
#

you could also just lean on the physics engine

random lodge
#

Currently the asteroids are moving down across the screen on their own. At the moment the ship only moves left to right. So as they move down the player would nudge them if they move left into them. I was hoping it would nudge/bump them at the angle the ship hits them from. Also want to possibly add some extra rotation from it.

#

Basically a Galaga type game but I'm adding a lot of deep intracies to everything's behavior

silver fern
#

then reflect could work

wintry quarry
random lodge
#

yeap they are, currently before I changed anything the behavior was a bit weird

#

They would kind of move through the ship and then go off course behind it

wintry quarry
#

what components does the ship have?

#

In this scnario I would give the ship a kinematic Rigidbody2D and move it via Rigidbody2D.MovePosition in FixedUpdate

random lodge
#

Like this at the moment

wintry quarry
#

ah that should work well

#

what shape is the collider?

random lodge
#

just like that at the moment

silver fern
#

you'll need a better collider

wintry quarry
#

use a PolygonCollider2D

random lodge
#

gotcha

edgy sinew
#

@wintry quarry long time no see! Awesome to see you still helping people here! ☺️

#

hey guys. Anyone ever experience a 55ms RenderLoop? & Is my Profiler looking brutal in general 🥲

balmy vortex
#

can someone remind me on how you check if a raycast you sent out actually hit anything?

#

and more importantly how you know what it actually hit

balmy vortex
#

thanks

rocky canyon
wintry quarry
limber turtle
#

i'm trying to make something like ultrakill's coins in 2d, would it be good to use FindObjectsWithTag and compare every item by proximity or is there an easier way to do this?

balmy vortex
#

or like how does this work

wintry quarry
limber turtle
#

bc if i do this in a room with lots of enemies in, it'll have to check the positions of every one of them until it finally finds the one closest to the object

polar acorn
silver fern
limber turtle
#

throw a coin, shoot it, it goes to the nearest active coin or the nearest enemy if there are no coins active

wintry quarry
limber turtle
#

alright

silver fern
balmy vortex
wintry quarry
wintry quarry
#

if it's a box shaped room, use OverlapBox

limber turtle
#

so should i just figure out what i want the maximum range for a rebound coin to be and then check for any enemy or coin inside that radius

silver fern
#

that would go through walls

limber turtle
#

oh shit yeah

#

what if i use a raycast to find whether or not the object is blocked by a wall

edgy sinew
#

Yeah that's exactly what I've done before

wintry quarry
#

yes exactly

limber turtle
#

alright

#

thanks

wintry quarry
#

or maybe CircleCast if you want it to have some "thickness"

limber turtle
#

i'll just set the maximum distance to be like 3x the camera's fov

#

so that way, it's far enough for you to not be missing against enemies you can see but not so far that you could snipe some poor bastard from 6 lightyears away with help from a convenient hallway

zenith cypress
# limber turtle throw a coin, shoot it, it goes to the nearest active coin or the nearest enemy ...

Seems you have it solved, but figured i'd drop info about it LUL It basically throws a coin (which has a collider obv), then when the revolver shoots it creates a beam object which handles the cast along its direction + other information, then then that beam "shoots" it checks what it hits (such as a coin which then just gets its component to run a function on it). And in that case, it's just a standard raycast with infinite distance. The coin itself handles any extra reflections off of itself when called from the beam.

limber turtle
#

but how does it find the right enemy to hit when there are multiple nearby?

#

or am i just being an undertale fan

analog pendant
#

Where to learn unity C# concepts. Any playlist or YouTube video

radiant voidBOT
edgy sinew
analog pendant
# edgy sinew What do you want to learn exactly?

I'm trying to make a tpp game, but unfortunately i stopped using unity 4 yrs ago and forgottenost of the things, although I'm good at modelling and all in blender. But now I want to know main concepts regarding tpp in unity

#

But only c# part

zenith cypress
random lodge
#

YouTube, Unity docs, Unity Learn, websites galore, C# websites, etc 😉 The glory of modern times. I remember when you had to mostly buy a book. It sucked. lol

edgy sinew
#

Let me find you some videos that helped me before

limber turtle
#

oh that makes sense

silver fern
#

what's tpp

limber turtle
#

does that not get intensive if you're in a room with like 500 filths

edgy sinew
#

Third Person Perspective

silver fern
#

oic

analog pendant
random lodge
#

I usually end up looking at 10 different sources for the same thing I want to figure out

analog pendant
#

So, I only have youtube option, I do read docs sometimes

zenith cypress
random lodge
#

Haha, Starlord and Galactus

limber turtle
#

i have no idea why i'm not using a coin list myself to be honest. i should add that

#

it'd make life a whole lot easier

edgy sinew
# analog pendant So, I only have youtube option, I do read docs sometimes

Unity Helpful Videos
Movement, Physics
https://youtu.be/NsSk58un8E0 (Advanced Movement Shooter Physics In 1 Hour)
https://youtu.be/jSauntZrQro (Anatomy of an Advanced Player Controller)
https://youtu.be/dLYTwDQmjdo (Unity3D Physics - Rigidbodies, Colliders, Triggers)
https://youtu.be/YR6Q7dUz2uk (Collide And Slide - Actually Decent Character Collision)
https://youtu.be/c1PAoxY7v54 (Basic third person controller)
Development Patterns
https://youtu.be/BwA36em_DnA (3 Game Programming Patterns WE ACTUALLY NEED)
https://gameprogrammingpatterns.com/singleton.html
https://gameprogrammingpatterns.com/state.html
https://www.youtube.com/watch?v=V75hgcsCGOM (Jason Weimann in-depth on State Pattern)

balmy vortex
#

like am I supposed to be seeing the raycasts or

zenith cypress
#

enable gizmos

limber turtle
#

also aren't the rays only visible in scene view, not game view?

zenith cypress
#

Both if you have gizmos enabled in each window

edgy sinew
#

@analog pendant those videos are a great place to start. Some of the Unity YouTubers go more in-depth into advanced stuff. git-amend for sure, Jason Weimann, Game Dev Beyond the Basics, others too.

limber turtle
#

oh

#

i should do that myself

#

thank you

balmy vortex
zenith cypress
#

Yes enable that. And if the ray is coming from the camera along forward, you will not see it. If that's the case, you can add a duration so you can move a bit and see it.

balmy vortex
limber turtle
#

float variable after the colour

#

defaults to 0

ivory bobcat
balmy vortex
#

Debug.DrawRay(transform.position, _camera.transform.TransformDirection(Vector3.forward) * 1000, Color.white, 5000);

#

am I doing smth wrong here?

limber turtle
#

gizmos in the corner of the game window isn't highlighted

polar acorn
balmy vortex
#

or am I missing smth

polar acorn
#

What calls DrawRay? Is that object actually in view?

balmy vortex
#

yeah it's the player object itself

#

the thing who's PoV you're seeing from

polar acorn
#

So, it's the player object, and it's pointing out straight along the center of the camera

#

I think you are getting the ray, but you're looking at it straight on.

balmy vortex
#

yeah?

polar acorn
#

Try pausing the game and looking in scene view

#

Where you can get another angle at it

balmy vortex
#

like they're there but I can't see them when actually playing for some reason

zenith cypress
#

(Also for future ref _camera.transform.TransformDirection(Vector3.forward) is just _camera.transform.forward)

#

gizmos are off

balmy vortex
zenith cypress
#

hmm, how strange

edgy sinew
#

MainCamera render settings culling mask?

limber turtle
#

it might be because i'm using 2d or something, i'm not sure, but it's working ok for me

#

there is a possibility we're on different versions but i'm not sure

zenith cypress
#

found this

#

Haven't found a report yet but at least one case

balmy vortex
#

this is not very sigma

edgy sinew
#

I use DrawRay all the time. I'm in Unity 6.2

queen adder
#

I dont need to put OntriggerEnter into update right?

edgy sinew
queen adder
#

okay thx

edgy sinew
queen adder
#

not a code thing but the player does not need to be a trigger, just the collier right?

zenith cypress
balmy vortex
edgy sinew
#

From ur own screenshot 😜

#

Have you had success with DrawRay before? I've done it in Unity 6.1 and 6.2, no issues ever

edgy sinew
rough blaze
#

I am trying to make a dash in my top down 2d game, I tryed probably four or five difrent methods how to implement it, followed a few tutorials...

balmy vortex
balmy vortex
rough blaze
#

and it just doesnt work, the script gets executed, but the player just wont move

#

here is the script

#

if (dashA.triggered && canDash){
StartCoroutine(Dash(Vector2.left));
}
if (dashW.triggered && canDash){
StartCoroutine(Dash(Vector2.up));
}
if (dashS.triggered && canDash){
StartCoroutine(Dash(Vector2.down));
}
if (dashD.triggered && canDash){
StartCoroutine(Dash(Vector2.right));
}

#

in the update methot

#

and a Ienumerator

limber turtle
#

that seems inefficient

rough blaze
#

IEnumerator Dash(Vector2 direction) {

    canDash = false;
    IsDashing = true;
    tr.emitting = true;
    currentDashTime = dashTime; // Reset the dash timer.
    startDashTime = Time.time;

    rb.AddForce(direction * dashSpeed * Time.fixedDeltaTime);

    yield return new WaitForSeconds(dashTime);

    tr.emitting = false;
    IsDashing = false;

    yield return new WaitForSeconds(dashCooldow);

    canDash = true;
}
wintry quarry
limber turtle
#

do you have seperate dash buttons for each direction?

zenith cypress
edgy sinew
# queen adder RB

What is the goal of using Trigger colliders? usually they are good for "player has entered zone" or things like that.

wintry quarry
queen adder
balmy vortex
wintry quarry
queen adder
edgy sinew
rough blaze
zenith cypress
edgy sinew
#

So, either the player has to detect if it's being attacked, or the enemy has to let the player know

#

Both methods have their advantages and disadvantages

rough blaze
# wintry quarry how does your regular movement code work?

void Update()
{
if (IsDashing) {
AirFriction();
}

    if(IsDashing == true){
        return;}

//movement
movement.y = verticalAction.ReadValue<float>();
movement.x = horizontalAction.ReadValue<float>();
//trigering dash
if (dashA.triggered && canDash){
StartCoroutine(Dash(Vector2.left));
}
if (dashW.triggered && canDash){
StartCoroutine(Dash(Vector2.up));
}
if (dashS.triggered && canDash){
StartCoroutine(Dash(Vector2.down));
}
if (dashD.triggered && canDash){
StartCoroutine(Dash(Vector2.right));
}

}

//movement execution
void FixedUpdate()
{
smoothMovement = Vector2.SmoothDamp(smoothMovement, movement, ref movementhSmoothVelocity, 0.1f);

    rb.MovePosition(rb.position + smoothMovement * MoveSpeed * Time.fixedDeltaTime);

}
balmy vortex
rough blaze
#

it is a simple movePosition

balmy vortex
#

is there any alternatives to it?

limber turtle
#

i think something like that is what fighting games do

#

saves you having the same line of code 3 times for each direction

wintry quarry
edgy sinew
#

MovePosition and MoveRotation are for Kinematic RB.
This allows Interpolation to still work.

AddForce and AddTorque are for dynamic RB.
This allows Interpolation to still work.

#

If you are going for non-kinematic RB, prepare to learn about PID. Springs, dampening. Integration, calculus all that

limber turtle
#

no worries

zenith cypress
rough blaze
limber turtle
#

yes

#

if your movement system involves setting the position every frame then external forces will not apply

edgy sinew
#

@rough blaze it looks like you might venture into "if statement hell" aka Code Smell "switch"
Sooner than later I recommend you try the State pattern

limber turtle
#

that's why if you want to make a more fluid movement system it tends to be best to use forces and change them to get the velocities you want, only setting velocities when it is appropriate to do so and won't override any other important movements

balmy vortex
balmy vortex
#

raycasts themselves work fine right?

#

it's just that they can't be drawn on the screen yes?

edgy sinew
#

Any reason you don't wanna go to Unity 6.2?

balmy vortex
#

I don't rly see a reason to if it's just this one thing that's broken

edgy sinew
#

Fair enough. Tbh i've been worried about frame stutter in Unity 6.2

silver fern
#

I have 6000.1.7 and draw ray works for me

edgy sinew
#

I feel like the Editor is slower. Not 100% sure but. Just a feeling

#

I can still get like 600 fps if I uncap framerate (-1), but still a frame gets dropped occasionally

#

So weird how the CPU and GPU are like <2ms, but a frame can be dropped?

#

⭐ hi guys, what is a good method for sharing constants between class instances?

Context
I am doing a bunch of Animator.StringToHash() on Awake
All the hashed values, need to be accessed by child instances of the parent class, StateOfMotion.cs
Hence all "sub types" need access to those same pre-hashed constants

#

Project-wide sharing, would I just make a static class and static variables?
Class-wide sharing, would that be static variables accessed like StateOfMotion.hash_IdleLoop1 ?

silver fern
#

static field?

edgy sinew
#

Sure, like in StateOfMotion.cs parent class?

#

So then the usage is like StateOfMotion.hash_RunLoop1?

silver fern
#

yeah

edgy sinew
# silver fern yeah

Any reason I would wanna do it that way instead of a Project-wide Constants.cs static class?

silver fern
hallow acorn
#

hey im trying to make a basic top down movement script with the ability to dash in any direction to gain a bit of a boost. this is my code know and while i know it doesnt work because the velocity added by the dash instantly gets overwritten by the normal movement, i dont really know how i should fix it. heres the code i use: ```cs
private void Update()
{
Vector2 direction = Vector2.down;

if (direction != playerControls.defaultMovement.Move.ReadValue<Vector2>().normalized)
    direction = playerControls.defaultMovement.Move.ReadValue<Vector2>().normalized;

if(playerControls.defaultMovement.Dash.WasPressedThisFrame() && currentDashCooldown <= 0)
{
    rb.linearVelocity += direction * dashSpeed;
    currentDashCooldown = dashCooldown;
    print(direction*dashSpeed);
}
else
{
    rb.linearVelocity = playerControls.defaultMovement.Move.ReadValue<Vector2>().normalized * movementSpeed;
}

currentDashCooldown -= Time.deltaTime;

}```

wintry quarry
hallow acorn
wintry quarry
#

use a timer or a coroutine to set it back to false when you're done dashing

hallow acorn
#

so its time based rather velocity based?

edgy sinew
#

A hybrid system can work too where it's a bit of both.

hallow acorn
hallow acorn
edgy sinew
#

For the actual resulting movement, you can allow some influence that combines with the hard-coded "dash amount" or "dash direction"

#

ASAP, I would switch to using the State Pattern though.

hallow acorn
#

state pattern???

edgy sinew
#

It's much easier to add dashes, vaults, "hard landings" after midair, and all that

#

Yeah have you ever used Enums before? It's similar to that

hallow acorn
#

how come as soon as i start something not very complicated i immediatly get overwhelmed haha

hallow acorn
edgy sinew
#

Like,
if (state == MotionStates.Idle) idleStuff(); else if(state == MotionStates.Running) runningStuff();

frosty hound
#

Making a custom character controller is very complicated

balmy vortex
#

anyone smarter than me know how to do this?

frosty hound
#

the out hit is what is hit

balmy vortex
edgy sinew
# hallow acorn a little bit but i never really understood them

using Enums for State is like the quick & dirty method. Basically an upgraded (if this, if that, if not do this, etc)
Typically a State machine works more like this

nextState = state.CheckForTransitions()
nextState = state.CheckForTransitionsPlayerControlled()
// if either above method said, time to switch to a new state
if (nextState != null)
    state = nextState```
frosty hound
#

And no, you cannot GameObject.Find as a way to compare something.

hallow acorn
balmy vortex
frosty hound
balmy vortex
#

sure

polar acorn
hallow acorn
#

thanks a lot im watching a yt video about it rn, ill look at this right afterwards!

edgy sinew
#

They literally came about as people tried to solve the issues in game making

polar acorn
#

Tag, component, something you can actually get some sort of feedback if it's incorrect

balmy vortex
#

well how do you check what tag an object has?

edgy sinew
polar acorn
balmy vortex
#

true

edgy sinew
#

Cheers wish u luck! We're always here to point in the right direction. 💪

balmy vortex
cosmic dagger
# silver fern do I need the effect class for this? If I return the effect in the Create() meth...

You would create two separate classes. An SO for the burn effect and a C# class for the runtime version of burn effect

    [CreateAssetMenu(fileName = "Effect_Burn", menuName = "hb/Effect/Burn", order = 1)]
    public class SO_BurnEffect : SO_Effect
    {
        public override Effect Create(EffectContext context)
        {
            return new BurnEffect
            {
                Power = context.Power,
                Duration = context.Duration,
                Frequency = context.Frequency,
                DamageController = context.DamageController
            };
        }
    }
    
    [System.Serializable]
    public class BurnEffect : Effect
    {
        public DamageController DamageController;
    }

This is an example, so it's barebones. You'd add other necessary fields . . .

balmy vortex
ivory bobcat
#

I'm assuming that you're actually trying to limit what you can hit.

ivory bobcat
#

Why do you need to compare names etc?

#

This looks very much like a xy problem

edgy sinew
#

@balmy vortex the idea is, different objects you collide with have different responses / behavior?

polar acorn
#

What do you want to do with the object your rays hit?

slow blaze
#

hey guys is there somthing like a nav mesh for 2D ?

#

I want to make the enemies track the player at all times and navigate around obstacles in the way instad of "walking" into the obstacle because the playeer is behind it

slender nymph
#

there's a navmesh plus package on github that makes unity's navmesh work for 2d, or there's aron granberg's A* Pathfinding Project which is another common alternative for 2d pathfinding (it also works for 3d)

shell sorrel
#

can get a little more complicated to define whats walkable and what is not with 2d

#

in the past i would just roll my own A* that works off of a grid or quad tree instead of a mesh and use extra properties on tilemap tiles to define whats walkable

limber turtle
#

is there a way to delete a specific item from an array without the index, or am i going to have to find the index somehow

#

i'm going to be cloning gameobjects, putting them in an array to keep track of them and removing them when the object is destroyed

#

and i can't find too much on array functions in c#/unity

#

all i'm finding is that it's not as good as python's

eternal needle
limber turtle
#

oh

#

i couldn't find that on the documentation

#

i'm getting an error

#

it's saying "GameObject[] does not contain a definition for 'Remove'"

#

or Add

#

are they not capitalised

silver fern
#

Remove is on list not on your object

limber turtle
#

oh

#

i don't know how to declare a list

#

i googled it and tried the first result i found and it didn't work

#

discord on my laptop is loading slow so it might take me a minute

eternal needle
limber turtle
#

well i've been learning c# for like a year or two now

#

i guess codeninjas is just shit then

#

before i was doing it like this:
public GameObject[] activeCoins;

#

but that doesn't give me the right results

eternal needle
silver fern
limber turtle
#

yes

#

i thought an array would work for what i am doing

#

apparently not

silver fern
#

array has a fixed size, list is dynamic

eternal needle
#

if you've been learning this way for a year or two, and you dont know the differences between arrays/lists, you should find a new resource to learn from. Do some c# basics outside of unity

limber turtle
#

oh that makes sense

#

well then what am i doing wrong with declaring my list?

#

it's saying there is no such namespace as list

real ferry
#

Import the namespace

limber turtle
#

from where

real ferry
#

Do you use rider

limber turtle
#

what's that