#💻┃code-beginner

1 messages · Page 672 of 1

split plover
#

like is it the character controller giving it the ability to use wasd?

#

I understand how its moving and all but i have no idea where to edit controls and stuff

naive pawn
#

Input is the old input system, aka Input Manager. its configuration is in project settings > Input Manager

wintry quarry
#

Input.GetAxis("Horizontal") the "Horizontal" input axis has the keys mapped to it in the project settings

split plover
#

Yeah i set it to both because i saw that

naive pawn
#

Horizontal and Vertical are part of the default configuration

wintry quarry
#

(and vertical)

split plover
#

Anyways thanks, i'll try to figure out a bit more about the input system package

tropic leaf
#

i can't seem to figure out why i am getting this error? i have UniTask in the package manager and these in my script

using DG.Tweening;```
here is my whole code
```c#
private async UniTask PanelFadeIn(CanvasGroup canvasGroup, RectTransform rectTransform)
{
    canvasGroup.alpha = 0f;
    rectTransform.localPosition = new Vector3(0f, -1000f, 0f);

    var moveTween = rectTransform.DOAnchorPos(new Vector2(0f, 0f), fadeTime).SetEase(Ease.OutElastic);
    var fadeTween = canvasGroup.DOFade(1f, fadeTime);

    await UniTask.WhenAll(moveTween.AsyncWaitForCompletion(), fadeTween.AsyncWaitForCompletion());
}```
wintry quarry
split plover
#

and also it seems much easier to use but

wintry quarry
split plover
wintry quarry
naive pawn
#

the new system is typically recommended

split plover
#

i looked into it and kinda realized it was pretty easy to understand both of them

tropic leaf
wintry quarry
#

eventually you'll want to learn the new system

wintry quarry
#

it's an extension method no doubt

split plover
shut swallow
#

for the third point: does it also applies when OnTriggerEnter? if so, should I place the 3D rigidbody on the object or the slash?

#

because I'm get getting any hits rn

polar acorn
#

Rigidbody is the component that actually calls the collider events, so at least one of them needs it

shut swallow
naive pawn
shut swallow
#

if(other.TryGetComponent<StandardEnemy>(out StandardEnemy T)) this should be able to grab the component of the collider right?

naive pawn
shut swallow
#

I know there's a difference but I'm not too sure how the syntax works even if I'm constantly refering to api lol

naive pawn
naive pawn
tropic leaf
#

even just UniTask does not exist

#

as a reference

wintry quarry
#

(with the .ToUniTask)

shut swallow
wintry quarry
#

is this for a melee attack? I really think using a collider and OnTriggerEnter is the wrong approach. Direct physics queries (.e.g Physics.OverlapBox) are more suited to it.

naive pawn
#

it drives collision for the existing non-trigger colliders

#

so if there's no non-trigger collider, there's no collision

tropic leaf
# wintry quarry can you show the code you're actually trying to write that isn't working?

here is my whole script. i am getting an error that "Task does not contain a definition for ToUniTask"

using System.Collections.Generic;
using System.Threading;
using Cysharp.Threading.Tasks;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;


public class NavBarUI : BaseUI
{
    [Header("Buttons")]
    [SerializeField] private Button mainMenu;
    [SerializeField] private Button shop;
    [SerializeField] private Button extra; // placeholder

    [Header("Animation")]
    [SerializeField] private float fadeTime = 1f;
    [SerializeField] private CanvasGroup mainMenuCanvasGroup;
    [SerializeField] private CanvasGroup shopCanvasGroup;
    [SerializeField] private CanvasGroup extraCanvasGroup;

    private CanvasGroup currentCanvasGroup;

    private void Awake()
    {
        mainMenu.onClick.AddListener(OnMainMenuClicked);
        shop.onClick.AddListener(OnShopClicked);
        extra.onClick.AddListener(OnExtraClicked);
    }

    private async UniTask PanelFadeIn(CanvasGroup canvasGroup, RectTransform rectTransform)
    {
        canvasGroup.alpha = 0f;
        rectTransform.localPosition = new Vector3(0f, -1000f, 0f);

        var moveTween = rectTransform.DOAnchorPos(new Vector2(0f, 0f), fadeTime).SetEase(Ease.OutElastic);
        var fadeTween = canvasGroup.DOFade(1f, fadeTime);

        await UniTask.WhenAll(
            moveTween.AsyncWaitForCompletion().ToUniTask(), 
            fadeTween.AsyncWaitForCompletion().ToUniTask()
        );
    }

    private async UniTask PanelFadeOut(CanvasGroup canvasGroup, RectTransform rectTransform)
    {
        canvasGroup.alpha = 0f;

        var moveTween = rectTransform.DOAnchorPos(new Vector2(0f, -1000f), fadeTime).SetEase(Ease.InOutQuint);
        var fadeTween = canvasGroup.DOFade(0f, fadeTime);

        await UniTask.WhenAll(
            moveTween.AsyncWaitForCompletion().ToUniTask(),
            fadeTween.AsyncWaitForCompletion().ToUniTask()
        );
    }

    private void OnMainMenuClicked()
    {
        if (currentCanvasGroup != null) PanelFadeOut(currentCanvasGroup, currentCanvasGroup.GetComponent<RectTransform>());
        currentCanvasGroup = mainMenuCanvasGroup;
        PanelFadeIn(mainMenuCanvasGroup, mainMenuCanvasGroup.GetComponent<RectTransform>());
    }

    private void OnShopClicked()
    {
        if (currentCanvasGroup != null) PanelFadeOut(currentCanvasGroup, currentCanvasGroup.GetComponent<RectTransform>());
        currentCanvasGroup = shopCanvasGroup;
        PanelFadeIn(shopCanvasGroup, shopCanvasGroup.GetComponent<RectTransform>());
    }

    private void OnExtraClicked()
    {
        if (currentCanvasGroup != null) PanelFadeOut(currentCanvasGroup, currentCanvasGroup.GetComponent<RectTransform>());
        currentCanvasGroup = extraCanvasGroup;
        PanelFadeIn(extraCanvasGroup, extraCanvasGroup.GetComponent<RectTransform>());
    }
}
wintry quarry
shut swallow
wintry quarry
#

I don't really have any idea what this image is showing to be honest or what you mean by attacks being suspended and "having individual casting"

shut swallow
ashen arch
#

zova, use a polygon collider for your slash. click the Edit Collider button (in Inspector) to adjust the points to the shape of the slash. add more points as needed.

wintry quarry
#

anyway I don't see how any of this is relevant to the actual collision detection. You seem to be talking about orchestration of the attacks

#

that's a separate concern

shut swallow
wintry quarry
#

it doesn't sound relevant to the question of whether you should be using a collider vs a direct physics query though

shut swallow
wintry quarry
shut swallow
#

ok, and how exactly should I do that 🫠

wintry quarry
#

when the attack happens, you do a direct physics query instead of enabling a collider and waiting for OTE callbacks

tropic leaf
lean berry
#

Hii!! I just joined this server and could really use some help with a small game I'm making for a college admission assignment. It's my first game ever, and I'm struggling a bit. I'm trying to create a waste collecting system where the player picks up waste items from the ground. Each item is either plastic, paper, or residual, and I want the corresponding counter to increase when one is picked up (So there are 3 counters). But I'm not sure how to properly set this up (with UI and scripting). If anyone could guide me or point me to the right direction, I'd be really grateful!!

hexed terrace
#

!learn would be a good place to start

eternal falconBOT
#

:teacher: Unity Learn ↗

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

lean berry
shut swallow
# wintry quarry when the attack happens, you do a direct physics query instead of enabling a col...

public class SlashBehaviour : MonoBehaviour
{
    [SerializeField] private int attackDamage = 1;
    [SerializeField] private PlayerCamera playerCamera;
    [SerializeField] private Transform cameraTarget;
    public LayerMask attackLayer;

    private void FixedUpdate()
    {
        SlashCollision();
    }

    void SlashCollision()
    {
        // values here are copied from player character
        var castCenterOffset = new Vector3(0, 0, 0.62f);
        var castCameraLocation = playerCamera.transform.position;

        var castCenter = playerCamera.transform.TransformPoint(castCenterOffset);

        // manually set - need to change if change vfx

        var vector3HalfExtents = new Vector3(1.25f, 1f, 1.25f);

        var updirection = Vector3.up;
        var slashDirection = castCenter - cameraTarget.position;
        var slashDirectionQuaternion = Quaternion.LookRotation(slashDirection, updirection);

        Collider[] hitColliders = Physics.OverlapBox(castCenter,vector3HalfExtents,slashDirectionQuaternion,attackLayer);
        int i = 0;
        while (i < hitColliders.Length)
        {
            // Output all of the collider names
            Debug.Log("Hit : " + hitColliders[i].name + i);

            if (hitColliders[i].TryGetComponent(out Enemy T))
            {
                T.TakeDamage(attackDamage);
            }

            // Increase the number of Colliders in the array
            i++;
        }
    }
}```
#

Cannot set playerCamera nor cameraTarget

shut swallow
#

mb

#

but yes

#

was working for a different script

hexed terrace
#

Type Mismatch happens when you've already assigned something, then you change the type in code. You can usually just drag and drop the required type to assign the new thing

shut swallow
#

but not this one

hexed terrace
#

if not, just click the field, press delete to clear it

shut swallow
#

I can't even see the Gizmo, the box isn't cast

rocky canyon
#

in Playmode?

shut swallow
#

both in scene and in game

rocky canyon
shut swallow
#

That's weird

#

let me breakpoint test it

rocky canyon
#

i did have abunch of errors when things weren't assigned (null checks are usually good to use in gizmo's) for when things arent assigned instead of a blanket (isplaying) condition

#

for example.. (not all the components that im needing are available? well, return out)

shut swallow
rocky canyon
#

if all the components are assigned and not null yea

#

it'll continue through it fine..

#

but if somethings missing (for example u forgot to assign one of the variables) it'll skip it instead of trying to draw.. (which would then just give u a null error in the console)

#

i mean.. thats not ur issue obviously.. just a little hint

#

make sure u dont have any console errors thats breaking the logic

shut swallow
#

is this a bug

rocky canyon
#

shaders take a minute to compile

shut swallow
rocky canyon
#

i wouldn't think so

rocky canyon
shut swallow
rocky canyon
#

the script breaks all to heck ^ thats y i use null conditions

#

soo if the enemy camera/target camera isnt assigned for a reason.. it'll just skip the GizmoDraw method w/o causing any errors

shut swallow
rocky canyon
#

weird.. when i tested it it didnt seem to make a difference where i put the target cam

shut swallow
rocky canyon
#

it just drew a box around the main cam

shut swallow
rocky canyon
#

ahh okay

#
[SerializeField] private Vector3 boxHalfExtents = new Vector3(1.25f, 1f, 1.25f);
[SerializeField] private Vector3 boxOffset = new Vector3(0, 0, 0.62f);``` also if u want to tweak and fine-tune the gizmo u can expose some of those values it uses in the inspector
shut swallow
rocky canyon
#

ya, i was gonna ask about that..

#

im using a Transform as the type there..

#

can u show the player w/ the PlayerCamera.cs script attached?

shut swallow
#

it works in another script

#

but not this one

rocky canyon
shut swallow
#

the player camera script just hooks up to the camera target so that it is always anchored

rocky canyon
#

like the box.. how is it supposed to be oriented relative to the camera?

shut swallow
rocky canyon
#

is this what ur trying to replicate?

shut swallow
#

sorta

#

aside from this

#

I also need to account for this:

rocky canyon
# rocky canyon

i had to tweak the maths a bit.. and have the box start at the midpoint between cam and target

shut swallow
#

if you looked a bit further up, a guy was talking about implementing overlapbox

rocky canyon
#

ya thats what i used

shut swallow
#

ah ok

rocky canyon
# rocky canyon

if u got any questions bout this clip and the code its using just give me a shout.. imma sit on it for a bit

shut swallow
rocky canyon
#

not a clue.. im happy to share my script. and the test objects

shut swallow
#

should I not pass the player camera fields

rocky canyon
#

if its only using the "position"

#

i wouldnt see why ud need the entire camera script

#

and it simplifies things if ur only using the transform

shut swallow
#

alright

#

it's working now

#

I used local values

rocky canyon
shut swallow
#

the despawn has a weird delay tho

rocky canyon
#

howso?

#

despawn of the enemy after health < 0

shut swallow
#

yea

#

probably an update thing

rocky canyon
#

ya, id suspect thats ur Enemy script logic

shut swallow
#

also on OnDrawGizmos, it isn't working because of this:

#

do I need to toggle this somewhere in the editor

rocky canyon
#

never seen that b4

#

nah, it should just work... theres

OnDrawGizmos() which will draw all the time..
and then theres OnDrawGizmosSelected() which will only draw when u have that gameobject selected

#

ahh local function is a hint..

#

you must have put it inside another function

shut swallow
#

lol

#

I realised

#

wrong brackets strikes again

little anvil
#

yo guys i have a problem...

using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class Player_Controller : MonoBehaviour
{
    //Initialize variables
    public float moveSpeed = 5f;                      // Speed of the player movement
    public float sprintSpeed = 10f;                   // Speed when sprinting
    private Rigidbody2D rb;                           // Rigidbody component for physics interactions
    private BoxCollider2D boxCollider;                // BoxCollider component for collision detection
    public GameObject cam;                            // Camera GameObject to follow the player
    private Animator animator;                        // Animator component for animations (if needed)

    void CamFollow()
    { 
        cam.transform.position = new Vector3(transform.position.x, transform.position.y, -10); // Camera follows player
    }
    public void OnWalkAnimationEvent()
    {
        Debug.Log("Walk animation event triggered.");
    }

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        boxCollider = GetComponent<BoxCollider2D>();  // Get the BoxCollider component for collision detection
        animator = GetComponent<Animator>();          // Assign the Animator reference
    }
    // Update is called once per frame
    void Update()
    {
        float moveX = Input.GetAxis("Horizontal");
        float moveY = Input.GetAxis("Vertical");
        float currentSpeed = (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) ? sprintSpeed : moveSpeed;
        rb.velocity = new Vector2(moveX * currentSpeed, moveY * currentSpeed);

        // Set the "Speed" parameter in the Animator to control animation
        if (animator != null)
        {
            animator.SetFloat("Speed", rb.velocity.magnitude);
        }

        CamFollow();
    }
}

For some reason the players Z-axis position is set to -10

naive pawn
#

did you perhaps assign the player into the cam variable

rich adder
#

btw normally camera following should occur in LateUpdate. And moving rigidbody should be in fixed update.
not exactly your issue right now but might want to fix that before it causes other weirdness later on

#

is this script AI generated? whats up with these comments lol
public float sprintSpeed = 10f; // Speed when sprinting

little anvil
little anvil
rich adder
little anvil
rich adder
little anvil
#

... what???

rich adder
little anvil
#

... what is fixed update?

#

i'm just a dumb man bro SORRY

steel smelt
#

a magic method to run in sync with the physics engine

#

num of physics steps per frame doesn't necessarily match the update loop, so you want to keep things playing nice with one another

little anvil
#

aight i'll check it out, thanks for the help

stoic summit
#

this script crashes unity, but only if certain pieces are added to map prefabs. pieces are all set up the exact same, using copied components from working pieces. Anyone have any ideas? ik it's coded like I'm a monkey

eternal falconBOT
stoic summit
#

sorry, had no idea how to do that lol, tried to figure it out

rich adder
#

paste code one of the links, save and send link

polar acorn
stoic summit
stoic summit
daring star
polar acorn
#

For example, if LastSpawned ever doesn't have children, you will crash

#

i will never increment

stoic summit
stoic summit
daring star
stoic summit
#

update, fixedupdate is for physics

daring star
rich adder
stoic summit
rich adder
#

what?

daring star
rich adder
rocky canyon
#

the one line of code is fine tho 👍

#

maybe debug the positions/vectors in the same function as the movetowards and see what gets outputted..

#

gonna/might shine some light on whats actually happen that isnt what u expect to be happening

rich adder
#

if the character is Rigidbody that line could be problematic no ? especially we cannot know how the camera itself is moved

rocky canyon
rocky canyon
#

say the target moves towards child.. (makes child move... == jitter/jank)

polar acorn
stoic summit
#

yeah, thank dawg

daring star
#

the problem was the dampling on cinemachine camera

wintry quarry
daring star
wintry quarry
#

on the object?

#

Also is that for the gun? What about the player?

daring star
wintry quarry
#

You should never modify the Transform directly for an object that has a Rigidbody.

scarlet skiff
#

I'm working on a weapon data system in Unity using ScriptableObjects, and I'm running into a design problem.

Originally, I had a WeaponThrowableData ScriptableObject, and from that I made child ScriptableObjects like WeaponThrowableBounceData and WeaponThrowableLingerData. The problem is: I couldn’t combine them. I couldn’t make a single weapon that had both bounce and linger behavior, because a ScriptableObject asset can only be one type. That forced me to choose one or the other.

Now I want to have a single WeaponData ScriptableObject that can support multiple roles playerWeaponData/enemyWeaponData) and multiple behaviors (bounce, linger, whatever else I add later). the obvious way to do that is by adding serialized fields for every possible type , but that means that a lot of times most of the fields go unused, and they still get initialized (right?).

Yes, I can hide the unused fields in the inspector with a custom editor, that’s not the problem. The problem is they still exist in memory and on disk even if they’re not being used. In a large game where this system is used everywhere, for all player and enemy attacks, I feel like that’s unnecessary bloat. now, its not thousands or even hundrereds of variables/fields, but if there is a way to improve i wouldnt wanna miss out on it.

What I’m looking for is a way to structure my ScriptableObject so that I only store and initialize the data I actually use, without having to split into dozens of ScriptableObject subtypes for every variation, becuase again, that doesnt even work, sometimes i need both types. Is there a proper way to do this that avoids wasting memory and scales properly? what do ppl do in this situation?

#

so basically what i have is first picture and i wanna have somethign that works like second picture

#

id appreciate any tutorials that talk about this, i cant really find the tutorials im looking for

wintry quarry
#

Also inheritance with SOs is a nightmare anyway

#

(for managing the assets)

bright osprey
#

you could break this down into a fluent builder style pattern (if im understanding what you want) and pass handlers into a class this way?

wintry quarry
#

So something like - your SO has a List<WeaponAttribute> where WeaponAttribute is a piece of data like you're referring to here.

#

the fluent/builder API is a convenient way to initialize objects but it doesn't actually address the architectural issue, no?

bright osprey
#

this was ontop of the avoiding Inheritance suggestion to be fair 🙂

bright osprey
scarlet skiff
#

i mean, i can have just like, SOs that are playerData, enemyData and stuff but then im creatign so many assets and its hard to keep track of

scarlet skiff
#

and id call init on onnetworkspawn or start in the bomb : weapon or wtv

#

i used to do stuff like if (data is WeaponThrowableBounceData bounceData) everytime i wanted to use a specifics datas fields before, this only needs to call init on initialization once, and if i have a manager in scene that collects and deactivates weapons rather than despawning them and spawning new ones, its not bad of a solution, less expensive i assume, but yea

#

if there are better ways, which i have a feeling there might be, id rather have that

wintry quarry
# scarlet skiff yea i tried to think of it as that but, that i came up with is not something i l...

you don't need all those things to be different classes. Just focusing on the float attributes for a minute, imagine a setup like this:

public struct Attribute {
  public string Name;
  public float Value;
}```
Then your weapon can look something like:
```cs
public class Weapon {
  public WeaponType weaponType;
  public List<Attribute> attributes;

  public Attribute GetAttribute(String name); // implement this with a dictionary or something
}```
And when processing things you can do a simple switch statement (or optionally, use delegates) to have different behavior per weapon type. For examplke:
```cs
void HandleWeapon(Weapon weapon) {
  switch (weapon.weaponType) {
    case BouncingWeapon:
      HandleBoucingWeapon(weapon);
      break;
  }
}

void HandleBouncingWeapon(Weapon weapon) {
  float wallBounceMultiplier = weapon.GetAttribute("WallBounceMultiplier").Value;
  float froundBounceMultiplier = weapon.GetAttribute("GroundBounceMultiplier").Value;
  float damage = weapon.GetAttribute("Damage").Value;

  // do your actual logic here
}```
scarlet skiff
#

the thing with structs rather than classes, structs are serializable, no?

wintry quarry
#

Both can be serializable

#

you can use classes if you want, it's not the main point here

#

this is quick and dirty. Enums may be better than strings. You need to handle non-float attributes, etc... but this is the basic gist of how I do it in my games.

#

you could have WeaponType be a list too

#

so you could then loop through all the types the weapon has

#

which is how you could combine e.g. Bouncing and other types in one weapon for example

scarlet skiff
#

wouldnt constantly having to loop to get a specific type of attribute be ineffecient

wintry quarry
#

to speed it up at runtime

#

hence my comment

#

that's just a performance optimization

#

let's focus on the architecture here 😛

white girder
scarlet skiff
#

okay guys, there is a lot to take in here for me give me a moment

scarlet skiff
#

in that case, how can you tell a class to deactivate fields, what is this fetaure called, or what can io search on youtube

white girder
#

Ngl I didnt read anything UnityChanOops

#

Thats how im trying to do it

#

Have one class that regulates when the smaller classes should do things

#

And the smaller classes just worry about doing their thing and dont have to worry about when to do it

scarlet skiff
#

sounds like jus ta parent/child typical set up

#

im trying to optimize as much as i can here, to the point if a weapon type, say bouncy, which require 3 different float values for a method in the weapon åarent class, is no being used, we dont even initialize those 3 variables for this specific weapon, it doesnt know about them

scarlet skiff
# wintry quarry you don't need all those things to be different classes. Just focusing on the `f...

so... we are creating a sort of dictionary out of this attribute struct and the serializable list?, and as long as we always name the values the same thing, like add an attribute struct with the name being wallBounceMult across all weapons that bounce, we can safetly access wallBounceMult across all bouncy weapons, this seems a little fragile, no? like leaves room for human error, having to type all these values everytime we create an SO with this list, or atp, no need for SO, this list of structs can be directly in thw weapon parent class

#

there was like some sort of asset, called odin i belkieve, that makes unserializable tpyes, serializable or something, among other features such as easier custom inspectors, but its 50$, i was planning on using it before finding out the price

wintry quarry
#

you don't need odin to make things serializable

#

you can do that just fine with the [Serializable] attribute

scarlet skiff
#

this is like, too fluid it feels like, i liked how it was a little more rigid before, premade values, is there no inbetween solution? or would such a solution compromise the technical effeciency of this

scarlet skiff
# wintry quarry yes there's some room for human error. It can be mostly mitigated with editor to...

what if we uhh like, keep the specific classes for data, like bounce, and add those as components on the gameObject, give them the data, then have those classes inherit from an interface IWeapon, and then we can keep the list of attribute, but have attrobite be like

public struct Attribute {
public string Name;
public IWeapon Values;
}

then we can weapon.GetAttribute("Damage").Values.wallBounceMult; or something, and to reference the IWeapons we just drag the script components to the list field in weapon class

austere monolith
#

my bad

wintry quarry
scarlet skiff
austere monolith
#

https://hastebin.com/share/uhimowoniy.csharp

for some reason when I look straight down and hold s, my player starts spam jumping, is there any way to block this off or something?

wintry quarry
#

It's a pretty big misconception

#

You can always optimize the performance later if it becomes a problem, but it won't

scarlet skiff
wintry quarry
#

You just tilt the camera

#

Most likely you screwed up your mouse look code and/or the setup in the inspector or hierarchy

austere monolith
#

i used a tut

wintry quarry
#

this code goes on the camera which should be a child of the player object

scarlet skiff
wintry quarry
# austere monolith https://hastebin.com/share/etahumicut.csharp sumin wrong?

There is ONE thing wrong with the code that is not related to this issue though - and that's the tutorial's fault:

        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;```
Time.deltaTime is absolutely wrong to have here. YOu shouldr remove it
#

and chang ethe sensitivity in the inspector asnd the code from 100 or so to 1 or so

austere monolith
#

alrightyo

#

thanks

#

whats the reason to not have Time.deltaTime there?

wintry quarry
#

it adds jitter for no reason

#

mouse delta input is already framerate independent

#

there is nothing to adjust

austere monolith
#

Oh, thats why my camera had random spikes of speed.

#

:/

wintry quarry
#

yes

#

removing it will fix that

austere monolith
#

well now I can't look horizontally? (im probably just stupid)

wintry quarry
#

what did you do

austere monolith
#

remove time.detlatime

#

wait a min

wintry quarry
#

did you move the scirpt to the camera?

scarlet skiff
austere monolith
#

nevermind

wintry quarry
#

Did you assign the player body correctly in the inspector to point at the main player object?

austere monolith
#

lol, i had to change the playerbody var to the gameobject

wintry quarry
austere monolith
#

idk, once the camera goes to like, 30 on the x rotation it does the weird skippy thing

wintry quarry
#

what weird skippy thing

scarlet skiff
austere monolith
#

i moved the script to the player transform capsule thing

#

nice

wintry quarry
#

with the script on the player transform you will have the jumping issue again

austere monolith
#

I mean the playermovement

#

on the capsule

wintry quarry
#

yes

#

playermovement belongs on the capsule

#

that's not the Mouse Look script

austere monolith
#

mhm thats what i did lol, i put the playermovement on the capsule and it worked. it previously was on the arms

#

the mouselook has always been on the camera lol

#

thanks for ur help

#

🙂

astral flame
#

Hello people if you can help me with my car code is that the car dumps when turning already tries to put this rb.Centerofmass = new vector3 (0, -1f, 0); But it skids a lot and does not let go of https://paste.myst.rs/v2gzmro1

scarlet skiff
#

blue 💔

astral flame
#

what?

scarlet skiff
alpine summit
#

I've made an overlay with a button that toggles my how-to-play screen (a UI Document in front of a background image). However, the button becomes unclickable when Background is enabled. The button is not layered behind the background so I'm not sure why this is the case

wintry quarry
#

So you're mixing UGUI and UITK?

alpine summit
#

it's just an empty object with an image component

rotund hull
#

How can i make an object so that the player can detect when they collide with it but the player cannot move it around, but the object can still collide with other objects

rotund hull
#

what does that do?

alpine summit
#

when it's active, the button becomes unclickable

wintry quarry
#

That's UITK

alpine summit
wintry quarry
alpine summit
#

oh, is there an issue with mixing UGUI and UITK?

wintry quarry
#

I don't know what the rules are for that but I wouldn't be surprised if you can't rely on the hierarchy order thing when you do that

alpine summit
#

ah, I see

#

is there some way I can force the button to always be clickable, or should I replace the UI Document?

wintry quarry
#

Or maybe there's something special you need to do. I would search the web with that mixing in mind

alpine summit
#

the reason I wanted to use it is because I would like to use a tab bar in my UI

#

because there is no ui tab bar in UGUI, right?

wintry quarry
#

There's no built in component for it but you could certainly build one

scarlet skiff
#

in case you were curios Blue, ive added this new system. List of IWeaponData (an empty interface), then data classes that inherit from it. with a custom editor script for WeaponData, i can serialize the list and its classes like this, so its componenet type of building for the weapon SOs, without the hassle from the previous approaches. I access these datas as such: data.Get<BounceData>() is BounceData bounce

the get method:

public T Get<T>() where T : class, IWeaponData
{
    return otherData.OfType<T>().FirstOrDefault();
}

honestly idrk how it works, but it does

acoustic belfry
#

Hey, if i want to put a value inside a function to wich another script will reference, and i want that script to call that animation, how i can do it?

#

what value i have to put?

#

i mean, like the

{
  animator.play(sightAnimation)
  detectedPlayer = true
}```
rich adder
# rotund hull what does that do?

actually.. how do you move the player , what components you have on it and why wouldn't regular collider work for the other object?

acoustic belfry
#

what would the [?] be?

eternal needle
acoustic belfry
# rich adder Could you clarify a bit more?

mmm, im using a base script for make my enemy scripts inherite it, and this function needs to call an animation, to wich the inherite has

the thing is, how i can call that animation in the function referenced?

#

i currently put string, but i feel like something may be wrong

eternal needle
acoustic belfry
eternal needle
acoustic belfry
#

i mean cuz when i put the values inside the () of the function it allows me to put animationClip, but of course when i try to put a name on it on the referencer doesnt work

#

anyways, so, in theory this should work?
base

    {
        animator.Play(sightAnimation);
        audioSource.PlayOneShot(sightSFX);
        detectoValeria = true;
    }```
referencer
```enemySight(animator, "MortemRifleSight", audioSource, troopersight);
#

let me rephrase, this should be the best way to do it, right? I mean cuz it works, but im always anxious abt if my scripts are well written or nah

eternal needle
# acoustic belfry let me rephrase, this should be the best way to do it, right? I mean cuz it work...

there isnt much to go off here to suggest anything different. if you want to directly play an animation, that is how you do it. Another thing you could do here is make more use of the animator controller and parameters
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Animator.SetTrigger.html
and then have it enter that state based on the trigger. Depends on how you wish to setup the animator

acoustic belfry
#

oh, i get it, well, thanks

alpine summit
#

just checking before I start making a prefab: it's possible to subscribe to a button-click event in code, right?

#

seems like it should be possible but I don't want to just assume before basing my code structure on that

brave robin
brave robin
alpine summit
#

System.Action

brave robin
#

Yup, += works for that

alpine summit
#

ok cool

brave robin
#

-= unsubs

alpine summit
#

very convenient syntax

brave robin
#

You can also get a full list of all listeners through its invocation list

#

Useful if you want to manually step through them and invoke that way

alpine summit
#

ArgumentException: GetComponent requires that the requested component 'Button' derives from MonoBehaviour or Component or is an interface. having trouble getting the button component of my tab button object

line with error: Button tabButton = tabGameObject.GetComponent<Button>();

#

where tabGameObject is a GameObject with a button component

polar acorn
alpine summit
#

UnityEngine.UIElements.Button

#

do I maybe need to use a different class for a TMP button?

polar acorn
alpine summit
#

ah

polar acorn
#

Unity UI button

alpine summit
#

I see, ty!

eager stratus
#

So I was told there was a way to pass arguments through button presses using the inspector. Is this true? If so, how do I go about doing this? Because all I see is a handler for an OnClick event that doesn't take parameters

teal viper
eager stratus
#

I'm trying to link it to a function that tells the button to disappear itself when it's clicked

teal viper
#

You can have a proxy button script that invokes the actual event with whatever params you want

#
public void OnClick()
{
  OnThisButtonClicked?.Invoke(this);
}
eager stratus
teal viper
#

Then just:

public void OnClick()
{
  otherObject.ThatOtherFunction();
  Destroy(this);
}
eager stratus
teal viper
#

You either reference it in the button or subscribe from that other script to the button. There's no way around it.

#

Someone needs to know about the other one if a function needs to be called on click.

eager stratus
teal viper
#

Yeah, well the code I shared does exactly that

#

You just set the reference to the other object in the attached script rather than the button itself.

eager stratus
#

There's no script on the button

teal viper
#

You add one

#

a proxy script like I said

eager stratus
#

And that's unavoidable?

teal viper
#

Yep. At least if you want the behavior that you described with minimal changes.

teal viper
# eager stratus And that's unavoidable?

If it's just destroying or disabling an object/component on click, you can add an additional OnClick listener/entry in the inspector with the appropriate call.

#

So that it invokes the specified function first and then does the disabling/destroying.

undone depot
#

can someone help out with why this knockback function isnt doing anything?

polar acorn
undone depot
#

how would i check that

teal viper
undone depot
#

it's only playing the first if statement, even if the object doesnt have that tag

fleet goblet
#

where can i learn how to code/make ai's enemys

rich adder
fleet goblet
teal viper
chilly mulch
#

In which app debug and code? visual studio 2022 or visual studio code!?

rich adder
#

either one works

#

vs2022 is windows only

teal elk
#

How woudl i ue unity tilemp rule tiles with my custom grid , i want to use unity tilemap ssytem with grid and rule tiles but i have mismatch issues, i dont want the custom grid on the rule tile edges only in the center , the code is to big to post here. any links an refence for help wuld be nice , thnak you

chilly mulch
rich adder
polar acorn
grizzled crag
#

    float moveDistance = moveSpeed * Time.deltaTime;
    float playerRadius = 0.7f;
    float playerHeight = 2f;
    bool canMove = !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * playerHeight, playerRadius, moveDir, moveDistance);


    if (!canMove) {
        Vector3 moveDirX = new Vector3(moveDir.x, 0, 0);
        canMove = !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * playerHeight, playerRadius, moveDirX, moveDistance);
        if (canMove) {
            moveDir = moveDirX;
        }
        else {
            Vector3 moveDirZ= new Vector3(0, 0, moveDir.z);
            canMove = !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * playerHeight, playerRadius, moveDirZ, moveDistance);
            if (canMove) {
                moveDir = moveDirZ;
            }
            
        }
    }
    if (canMove) { //Can move both directions
        transform.position += moveDir * moveDistance;
        
    }
    isWalking = moveDir != Vector3.zero;
    transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * lookSmoothing);

}

This code detects if there's an object in front of the player. If it sees there's one, it'll check the z and the x axes if thoses axes are clear. If they are, the player will only move in those directions. Upon testing, there are instances where when I hit two movement keys (W, A or W, D), it ends up going through the wall as if there was no collision at all. Is there anything I can do to make this script more reliable?

undone depot
solemn crypt
#

Need help load scene

#

What do I do ?

#

I’m trying to change levels with canvas

#

Button

#

Using unity 6

teal viper
eternal falconBOT
solemn crypt
teal viper
#

In where?

solemn crypt
#

Do I show you what I’m working with here ?

teal viper
solemn crypt
#

Or available even

#

It was like why?

teal viper
#

I have no clue what you're trying to say. If English is difficult for you, use a translator.

solemn crypt
#

It said that the scene was not available to load

#

But idk I’m trying to figure it out

teal viper
undone depot
supple flume
#

chat, i want to achieve an if statement with 2 ifs, only one of them can be true, NOT both , is there away to do it without putting an and where they both are correct?

#

Crazy active chat ong

stuck field
#

if (a) {} else if (b) {}

supple flume
stuck field
supple flume
#

so i want it like this

supple flume
stuck field
supple flume
# stuck field Why is that?

its an equation let me write it for u

math.abs(agagag.indicatorx - pet.sitOnx) == 1 && math.abs(agagag.indicatorY - pet.sitOny) == 0

#

this is an example

#

those are not the intentional values

stuck field
#

Still can have an else if, that statement won't work either as it will only return true if x is 1, and y is 0

#

That's not going to be the case always

supple flume
teal viper
#

I mean, you can go for something atrocious like if((a || b) && a != b), but an else if is probably gonna be more readable.

supple flume
#

can anyone provide an example for the if else, cause i couldnt think of it

#

i thought of the if(( ) &&) but as i said i want smth cleaner

stuck field
teal viper
#
if(a)
{
}
else if(b)
{
}
naive pawn
supple flume
#

how couldnt i thinl of this 💔

split plover
#

Quick question, if not setting something like a function or integer to private does the same thing as setting an integer or function to private, why would i type private on things like integers or functions

iron wind
split plover
#

Well i dont think im gonna be finding myself using public too much anyways because outside of when i specifically need to access something in the inspector or in another script i probably will just add it layer if i need it

#

so it seems more useful to just remember they exist and not use them until i need them

sour fulcrum
#

private by default yee

#

you can also do [SerializeField] before a private field to make it show up in inspector like what public does

split plover
iron wind
#

no

split plover
#

Okay thats useful

#

I'll starrt using serialize field for some stuff instead of making 90 things public

iron wind
#

it's only to make unity serialize the value and show it in the inspector

sour fulcrum
#

No explicit access modifier means private

[SerializeField] doesn’t affect accessor at all

#

[SerializeField] is technically unity magic where unity secret breaks in regards of the lock 😄

west sonnet
#

I have a player body with a movement script on it. I have a camera parented to the body, which has a mouse movement script on it. Problem is, when I move forward the player body moves forward in whatever direction I'm facing. So if I look up and press forward, it'll jump up rather than moving forward. If I look down, it tries to move into the ground but it cant so it doesn't move at all.

I've tried to fix it but can't. If anyone could please help I'd appreciate it. Here are the scripts:

PlayerMovement: https://paste.mod.gg/kolozwbclfsc/0
MouseMovement: https://paste.mod.gg/

keen dew
#

The obvious solution is to use the player body's transform for movement instead of the camera's

west sonnet
#

I'm not sure what you mean. The movement script is on the player body. The mouse movement (looking around) is on the camera

keen dew
#

Yes but you use the camera transform for movement

#
Vector3 Move = Camera.transform.right * X + Camera.transform.forward * Z;
west sonnet
#

Vector3 Move = transform.right * X + transform.forward * Z;

#

Should I change to this? ^

keen dew
#

If this script is on the object you want to base the movement on then yes

west sonnet
#

So looking around doesn't rotate my player

keen dew
#

You'll have to change what looking around does then

#

This is why usually looking up/down rotates the camera and left/right rotates the model

west sonnet
#

I'm not super knowledgable on Quaternions or Eulers so I'm not sure if I 've written it in the best way here

keen dew
west sonnet
#

Does it make sense to apply 2 Quaternion.Eulers here?

keen dew
#

Sure, they apply to different objects so no avoiding that

supple flume
#

ok so yall another question, how do i check if a number is one of the sizes of an array

#

im using a 2d array and i want lets say to check if 5 is one of its dimentions

wintry quarry
supple flume
#

what does the word iterate mean

#

lol

wintry quarry
wintry quarry
supple flume
#

oo

thorn stone
#

Anyone sees whats wrong

#

Cus it aint moving

slender nymph
#

you need to get your !IDE configured 👇

eternal falconBOT
thorn stone
slender nymph
#

having configured tools is a requirement for getting help here

#

!collab 👇

thorn stone
#

Whatt

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

thorn stone
#

Ohh

#

Alright then

brazen dragon
#

ok sorry

barren vapor
thorn stone
#

Yeah nothing works

barren vapor
#

White circle next to your filename means that it's unsaved

thorn stone
#

I am reseting to some step back

naive pawn
#

have you configured your ide

thorn stone
#

No

naive pawn
#

configure your ide

thorn stone
#

Which one

thorn stone
#

@naive pawn

rich adder
slate summit
#

i have a question, can you have a empty C# script instead of c# sharp script or r they the same?

thorn stone
#

Bro what the hell is this

#

I will freaking set up this shit for another 3 hours and get no help from it

rich adder
thorn stone
#

What will it even do

rich adder
#

did you read the Bot message

#

it tells you mostly why

#

if you're confused on simple step by step guide on a configuring IDE, gamedev isnt much easier

rich adder
slate summit
rich adder
naive pawn
thorn stone
#

I am fucking stuck on fucking script

rich adder
thorn stone
#

I have been working fucking 10 hours straight

#

And this shit doesnt fucking work

rich adder
#

then take a break instead of being an ass

slender nymph
slender nymph
#

then go cry somewhere else

thorn stone
#

I am so close to say something that would make me get banned from Discord for TOS violations.

fickle plume
eternal falconBOT
#

dynoSuccess mintysmelon was muted.

rich adder
#

asking for help then insulting people who try to help.. A+

frail hawk
#

why mute and not ban?

#

insulting people who trying to help out is a no go

fickle plume
frail hawk
#

fair enough, right choice

slate summit
#

Can someone help me with this code?

#

what do i need to fix?

fickle plume
#

Also you can mouse over error it will tell you that

frail hawk
#

!IDE @slate summit

eternal falconBOT
slate summit
#

ok tysm!

sharp bloom
#

Hi, need help with the grid component. I spawn the "floor" tiles using a for-loop with grid.GetCellCenterWorld().
I want to spawn the cubes on the cells with grid.CellToWorld() but as you can see they're not alligned correctly. Probably did something stupid here.

#

The tiles are just these sprite prefabs, (rotation is for orthographic camera)

#

And I generate grid as

private void GridGen()
        {
            for (int i = 0; i <= sizeRows ; i++)
            {
                for (int j = 0; j <= sizeColumns; j++)
                {
                    var position = gameGrid.GetCellCenterWorld(new Vector3Int(i,j));
                    var cell = Instantiate(cellObj, position, cellObj.transform.rotation);
                    cell.transform.SetParent(visualGrid.transform);
                }
            }
        }
naive pawn
#

also btw you can set the parent in the Instantiate call directly

sharp bloom
#

I think the problem is the how I setup the grid lines. This is a default cube at (0,0,0) where the grid also begins.

#

Seems the origin of the sprites is the bottom left corner

naive pawn
#

so the pivot of the cube is at the center, presumably

sharp bloom
#

Yes

naive pawn
#

the grid lines outline the edges of the grid cell, so GetCellCenterWorld should be correct to position the cubes within the grid cell

#

oh i misread

#

i see the issue now

#

your floor tiles use GetCellCenterWorld, while your cubes are CellToWorld
just change one to be the other

#

probably change the latter to GetCellCenterWorld

sharp bloom
#

Oh yeah that was simple, thank you, I have no idea why I used different methods XD

viscid girder
#

The trigger sets off and shows it in the preview yet it still doesn't play when I left click?

naive pawn
#

please don't crosspost

viscid girder
#

mb, wasnt aware

naive pawn
#

please do remove all the duplicate posts as well

hasty tundra
#

Is there a way to restrict the input into a TMP input field so that it can only be numbers?

rich adder
#

iirc "Content Type"

supple flume
#

why do i get an error saying there isnt an instance

#

omori dude who kept helping me wya

#

My array has 4 objects

#

BUT dont arrays start with 0?

#
  • i tried to do it as 4 and same thing
eternal needle
eternal falconBOT
supple flume
#

entire code is a miss like hella

#

the fore loop is 103

cosmic dagger
supple flume
#

highschool lied to me

eternal needle
cosmic dagger
#

The number you provided indicates the array's length, which is 3. When indexing an array, you start at 0 . . .

supple flume
eternal needle
# supple flume the ag assigning line

well if you really cant be bothered to show the code properly (the bot instructions above) i really cant be bothered to help.
The code isnt lying to you, something is null and you are trying to GetComponent on null then

supple flume
#

got backlashed a lat when i showed my old missy codes

#

so another question, how do i know the length of one side of the array, Using the length value gave me the amount of items stored, all i want is what is the maximum amount in each collumon in a 2d array

#

and rank gave me what type of array is

eternal needle
#

if it was an issue with the index, the error would also be like this:
System.IndexOutOfRangeException: Index was outside the bounds of the array. not an object instance being null

supple flume
eternal needle
supple flume
#

so every 2d array has [, ] right

#

i want how much is the max value of the sides

eternal needle
# supple flume i want how much is the max value of the sides

i dont really know what you mean by max value of the sides, but from your initial question "length of one side" would be .GetLength and you pass in the dimension like 0 or 1. Basically getting the amount of rows or columns if you view it like a matrix

supple flume
#

Not their amount

#

the amount of them

eternal needle
#

yes my answer above also tells you how to do that, right in the middle of the sentence

#

".GetLength and you pass in the dimension like 0 or 1"

mystic glacier
#

👋

#

When my character is stepping off a platform, it acts like it's walking down a smooth mountain (slope) and doesn't jump me off from the platform directly. How can I fix this behaviour?

polar acorn
#

Sounds like you're resetting your y velocity to 0 every frame

mystic glacier
#

The condition is isGrounded && velocity.y < 0

#

Am I doing it wrong?

polar acorn
eternal falconBOT
mystic glacier
#

Here you go: https://paste.mod.gg/skbpqfmepleq/0
Please keep in mind that I used AI to help writing code but I didn't fully copy-paste it, I'm trying to understand the code while using AI, it's just that I'm new to game dev and not fully familiar with it

polar acorn
#

Attempting to scroll on that website on mobile attempts to edit it and clears the entire thing. I'll have to leave this for someone who can actually look at the code

polar acorn
#

Better, I can actually open that one

#

You are calling .Move twice. You should do it one time with both the horizontal and vertical movement. Otherwise, your isGrounded checks will not work properly

hazy crypt
#

Hey guys, I have a question about applying text effect for a menu, where would I ask about that?

mystic glacier
hazy crypt
polar acorn
#

I'm trying to follow everywhere velocity is set and used but searching on that page only searches what is currently on the screen and I just shouldn't try to review large code files on mobile because none of these sites work with it

#

But I did notice the double calling of Move, maybe that'll be enough

#

With it double called it would basically only detect is grounded every other frame

mystic glacier
#

Didn't work sadly, when I'm walking off the platform it still acts like I'm walking off a slope and slowly decreases the Y position

#

characterController.Move((moveDirection + velocity) * Time.deltaTime); changed it to this fyi

mystic glacier
stray oyster
#

I folks I wanted to check if there is a built in tool for a weird mechanic for a 2d game.

Essentially I want something that acts like those CSS sliding image comparison tools, but where the dividing line rotates like the edge of a shadow as a light source moves around a corner. And to make things complicated I would want multiple slider bars, so it’s not showing parts of two layers, but parts of multiple layers.

I think my current options are:

  • use the shadow tool, where light makes a layer opaque and shadow makes transparent showing the other layers, and figure out where light blocking elements need to be for each layer.
  • use multiple sprite masks, one for each layer, and reshape the sprite masks as needed.

So what do you all think?

inner crane
#

Hello does anyone know why my rb has some kind of delay when releasing the movement key? its only when i normalize the vector which doesnt make much sense for me. I couldnt really find a solution online so maybe someone could help me

timid salmon
#

Dose Anyone know why my bulletcooldown isnt working

inner crane
ripe shard
rich adder
timid salmon
ripe shard
#

but you only want to start one cooldown

#

you could for example move that StartCoroutine of the cooldown into the if (ButtonPress) {}

timid salmon
#

public class ShipGun : MonoBehaviour
{
public Rigidbody bullet;
public int bulletPower;
public bool bulletCooldown;
void Start()
{
bulletCooldown = true;
}

void Update()
{
    if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.right), out RaycastHit hitinfo, 10f))
    {
        Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.right) * hitinfo.distance, Color.green);
    }
    else
    {
        Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.right) * 10f, Color.red);
    }

    if (Input.GetMouseButtonDown(0) == true && bulletCooldown == false)
    {
        Rigidbody clone = (Rigidbody)Instantiate(bullet, transform.position, transform.rotation);
        clone.linearVelocity = Vector3.forward * bulletPower;
        bulletCooldown = true;
    }

    if (bulletCooldown == true)
    {
        StartCoroutine(BulletCooldown());
    }
}

private IEnumerator BulletCooldown()
{
    yield return new WaitForSeconds(1);
    bulletCooldown = false;
}

}

#

theres the code so just copy paste and show me where i should put it

#

im more of a visual learner

eternal falconBOT
timid salmon
#

could you do that?

timid salmon
rich adder
timid salmon
#

how do i send it

rich adder
timid salmon
#

is that good

rich adder
timid salmon
#

what do i do🙏

rich adder
#

delete this and send it properly through a link

timid salmon
rich adder
timid salmon
rich adder
#

what do you mean where ?

#

did you read what they said

#

look at your code...where do you have if (ButtonDown)

#

btw in an if statement == true is the deafault check so it can be omitted

timid salmon
#

Yeah

#

Would I Do - if (Input.GetMouseButtonDown(0) == true && bulletCooldown == false && StartCoroutine(BulletCooldown() == true)

timid salmon
#

idk then

rich adder
#

if you're confused you outta start for simpler projects / code on !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

rich adder
#

you lack basics of c# you should probably do that first before making a game

timid salmon
rich adder
# timid salmon can u just show what it wold look like

I mean that won't really teach you much..

 if (Input.GetMouseButtonDown(0) && bulletCooldown == false)
        {
            Rigidbody clone = Instantiate(bullet, transform.position, transform.rotation);
            clone.linearVelocity = Vector3.forward * bulletPower;
            bulletCooldown = true;
            StartCoroutine(BulletCooldown());
        }```
rich adder
#

if you are comparing this to what you sent and somehow think its the same, again.. you need c# basics

timid salmon
#

But I tried another way which is when i came on here to ask for help

timid salmon
#

ill try it out cuz im not disagreeing with u when u say i need help

#

ty tho

rich adder
#

what you sent the first time had StartCoroutine(BulletCooldown()); Inside UPDATE not the IF ButtonDown Block

#

so as long as bulletCooldown was true, which it was until; 1 second each time, it kept starting a new one each frame

mystic glacier
eternal needle
mystic glacier
#

This is what I mean

eternal needle
#

that looks about how i would expect it to function

mystic glacier
mystic glacier
eternal needle
teal viper
# mystic glacier

I don't think this platform is high enough to demonstrate anything. The capsule still collides with it, while it's going down, do you're probably still grounded.

mystic glacier
#

Oh, so it's because of the capsule collider shape?

teal viper
#

Yes. Try make it a lot thinner and see if it changes.

mystic glacier
teal viper
mystic glacier
teal viper
#

I was talking about the capsule, not the platform

mystic glacier
#

Oh 😭

#

Sorry it's 4 AM, my brain isn't really processing stuff

teal viper
#

If you want to modify the platform, then make it higher, not lower.

undone depot
#

how can i access a component on an object thats completely unrelated to where my script is attached?

celest ore
#

@slender nymph can u share me that webpage where the ways of properly questioning were written?

#

it was something like "the question you think is a question but its not", "be specific"

slender nymph
#

the Don't Ask To Ask site? that doesn't really tell you how to formulate a question. it just explains why asking to ask a question is pointless

hasty tundra
#

Hi, using steam achievments here. i need to be able to get the icon for an achievment and use it as a sprite in game. I know this would be done with GetIcon() but am not sure on the syntax, and i cant find it anywhere.

slender nymph
#

how you get that is dependent on the asset you are using for steamworks integration. consider looking at its documentation or whatever support channels are available for that asset

undone depot
#

how can i access animations in script?
i tried to reference the animator, object, and controller but none of them seem to work

frigid sequoia
#

So, ah, this is a dropdown and I am getting in the OnValueChanged() that, if I am not mistaken returns the index of whichever is the index of the option chosen on the value change. So my question is, what is the number input field for in here?

#

Can I manually give it a value or what?

eternal needle
slender nymph
undone depot
#

im trying to find where to reference the animation so i can use animation.stop()

frigid sequoia
slender nymph
#

only the top ones get whatever is passed directly at the invocation of the event. the bottom gets whatever is specified in the inspector

frigid sequoia
#

Wow, so that dropdown tooltip is gonna end looking extremely big lol

eternal needle
frigid sequoia
#

Cause I am gonna have all the methods showing on duplicate on there then

#

And they are gonna be a bunch sadly

slender nymph
#

that likely means the component is doing too much

frigid sequoia
#

I find it pointless to have a different script to set any and all of the different parameters I need when they are gonna just function exactly the same anyways

#

They all just work the same, but affect a different parameter on the manager

hollow palm
#

Hi, is anyone here using Visual Studio Community as their editor? I prefer creating new classes through VS rather than the Unity Editor because it's faster with the Ctrl + Shift + N shortcut. However, a new issue arises when using a custom snippet to write the initial MonoBehaviour template, the class name doesn't automatically match the file name, so I have to manually update the class name. Is there an efficient way to handle this?

As far as I remember, VS Code has an extension for this, but I’m not sure about Visual Studio Community.

quartz hound
#

there isnt a {FileName} in the shortcut? thats odd

hollow palm
#

pardon?

quartz hound
#

usually they have added definitions that you can use to autofill

hollow palm
#

this is the snippet i use

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Unity MonoBehaviour</Title>
      <Shortcut>MonoBehaviour</Shortcut>
      <Description>Code snippet for a MonoBehaviour class</Description>
      <Author>John Miller</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Code Language="csharp">
        <![CDATA[public class $name$ : MonoBehaviour
{
    
}]]>
      </Code>
      <Imports>
        <Import>
          <Namespace>UnityEngine</Namespace>
        </Import>
      </Imports>
      <Declarations>
        <Literal>
          <ID>name</ID>
          <ToolTip>Class name</ToolTip>
          <Default>MyMonoBehaviour</Default>
        </Literal>
      </Declarations>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>
quartz hound
#

$name$ is what you want

#

there should be a way to make it the file name

hollow palm
#

do u know how?

quartz hound
#

it will be tool specific so sadly not

hollow palm
#

It quite surprising that VS Code offers more enjoyable features compared to the full featured IDE itself.

quartz hound
#

give people the tools and they will build

versed light
#

why does unity have overload for set vertices and set uvs to use native arrays but not for set triangles

snow trail
#

does anyone recommend any tutorials, I wanna learn code :P

naive pawn
eternal falconBOT
#

:teacher: Unity Learn ↗

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

snow trail
#

tysm!!

quartz hound
#

I loved learning basic code tinkering skills
kind of miss those days

winged seal
#

could anyone tell me how i could make my Battering Ram and SledgeHammer be able to knock a door down?

#

And also its in vr

charred spoke
#

if(sleehammer hits door) then KnockDoorDown()

timber tide
#

How do rigidbodies usually work in vr? If the player was controlling the hammer would you just apply your own physics I guess?

charred spoke
#

But to be more serious you could probably apply a breaking force to the hinge joints of the door

#

The wall it depends on how procedural you want the destruction to be

winged seal
#

i want to press B then it kicks the door

median hatch
#

there are some packages for mesh destruction

#

but if youre asking how to trigger something with colliders maybe you should start there

timber tide
#

Can chop up a door in blender and keep it glued together inside of a prefab then throw on rigidbody onto each part then when the hammer collides you activate the bodies

#

or more performant way is to swap out the door with the chopped up door

scarlet skiff
#

attack animation is being cut off by itself replaying not allowing the last animation event to be called, and for attack to be called too many times. checking in set animation if the current sdtate matches the last and if it does, return, shouldve solved this issue.

code: https://paste.ofcode.org/EA5JWzJA79HRjR3gkqKwVM

strong shoal
#

how do i fix a redundant varible???

rocky canyon
#

delete it

dense rampart
#

genial!

winged seal
#

something like this

rocky canyon
#

🔍 : unity mesh destruction github should yield a good amount

winged seal
#

i mean like so it just opens up fully

#

not falling apart because performance reasons

rocky canyon
#

well if it only needs to open.. isn't it just a regular door at that point?

winged seal
#

i need it to open when i kick it or when i use my battering ram.

rocky canyon
#

well still.. thats just a door that pivots, either with code or animation
and then a basic interaction script / raycast / overlapsphere/ trigger etc

#

in collider -> kick input press -> open door

winged seal
#

no code needed for the battering ram?

winged seal
#

it has a pivot tho

#

i did try a code

#

but its not really moving

rocky canyon
winged seal
#

so it opens when something collides against it?

rocky canyon
#

well right now its just a boolean i flip on and off in the inspector

#

but once i get around to doing the interaction all i need to do is reference that script ^ and set its boolean to true

#

then it'd fling open..

#

i can control the speed and the angle

winged seal
#

using UnityEngine;

public class KnockableDoor : MonoBehaviour
{
public float knockForceThreshold = 5f;
private Rigidbody rb;
private bool knockedDown = false;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void OnCollisionEnter(Collision collision)
{
    if (knockedDown) return;

    // Only react to tools with Rigidbody
    Rigidbody otherRb = collision.rigidbody;
    if (otherRb != null && collision.relativeVelocity.magnitude > knockForceThreshold)
    {
        if (collision.gameObject.CompareTag("BatteringRam") || collision.gameObject.CompareTag("Sledgehammer"))
        {
            KnockDoorDown(collision.relativeVelocity);
        }
    }
}

void KnockDoorDown(Vector3 force)
{
    knockedDown = true;
    rb.isKinematic = false;
    rb.AddForce(force * 50f); // add knockback
}

}

rocky canyon
#

for animation you'd animate the door using the animator.. (insert a keyframe at the very beginning where its closed.. and then adda keyframe at the end when its fully open)

#

and then its the same.. u access the Animator component and set a bool or a trigger to control the transition

winged seal
#

where is the animator at?

rocky canyon
#

and run it and see whats getting logged and what doesnt get logged

winged seal
#

okay 1 second

#

here :

using UnityEngine;

public class PlayerKicker : MonoBehaviour
{
public Transform kickOrigin;
public float kickDistance = 0.5f;
public float kickSpeed = 0.1f;
public float kickCooldown = 0.5f;
private bool canKick = true;

void Update()
{
    if (canKick)
    {
        Debug.Log("Can kick: TRUE");
        if (Input.GetKeyDown(KeyCode.B))
        {
            Debug.Log("Kick button pressed");
            StartCoroutine(PlayKick());
        }
    }
    else
    {
        Debug.Log("Kick is on cooldown");
    }
}

System.Collections.IEnumerator PlayKick()
{
    Debug.Log("Kick started");
    canKick = false;

    Vector3 originalPos = kickOrigin.localPosition;
    Vector3 targetPos = originalPos + new Vector3(0, 0, kickDistance);

    float t = 0;
    while (t < 1)
    {
        t += Time.deltaTime / kickSpeed;
        kickOrigin.localPosition = Vector3.Lerp(originalPos, targetPos, t);
        yield return null;
    }

    Debug.Log("Reached forward kick position");

    t = 0;
    while (t < 1)
    {
        t += Time.deltaTime / kickSpeed;
        kickOrigin.localPosition = Vector3.Lerp(targetPos, originalPos, t);
        yield return null;
    }

    Debug.Log("Kick pulled back");

    yield return new WaitForSeconds(kickCooldown);
    canKick = true;
    Debug.Log("Kick ready again");
}

}

cosmic dagger
winged seal
#

!code?

cosmic dagger
#

Uh oh, bot down?

rocky canyon
naive pawn
cosmic dagger
# winged seal !code?

Basically, use a paste site to save from taking up space in the chat, especially if your code is large . . .

rocky canyon
#

animate within a wrapper container.. so u can move it around and reuse it w/o the animation locking it in place..
(you animate the child (door hinge).. that way we can move around the door gameobject and still have it open and close..

you set up parameters for the animator to use for transitions.. transition from door idle -> door open.. and maybe door open -> idle.. and then u just reference tha animator in code.. and set the bool there

naive pawn
#

(bot down, even the status page gives a 522)

winged seal
#

it aint working

#

but i really need to get my code to work today

rocky canyon
#

what isn't working?
thats like taking ur car to a mechanic and just telling them its broken..
no sounds, no codes, no nothing

cosmic dagger
rocky canyon
#

lol

rocky canyon
#

any logs, any console errors?

winged seal
#

no errors with the code

cosmic dagger
#

So we have a link from you of your code to see what the problem is . . .

timid quartz
#

I'm trying to make a Unity game that uses some stuff in the Android.Content namespace but am not sure how to include that stuff correctly into my code. adding using Android.Content; to the top isn't working correctly and I don't know how to install or find what I'm missing. The Android build tools are installed and I can export the game to apk, but I feel like I missed a step somehow to access the Android namespace in C#

timid quartz
#

NFC reader - and it looks like what I was missing was adding the android.mono dll to the actual assets folder

#

it was installed through dotnet but not actually included in the unity project

#

thanks anyway for following up!! 🙂 ❤️

high summit
#
    void Update()
    {
        timer -= Time.deltaTime;

        if (timer <= 0f)
        {
            bool newState = !lightOB.enabled;
            lightOB.enabled = newState;
            emissiveMaterial.SetColor("_EmissionColor", newState ? Color.white : Color.black);
            timer = Random.Range(minTime, maxTime);
        }
    }
#

Have this issue with this flashing light script dropping fps when enabled, any ideas?

#

maybe I should switch to a coroutine?

naive pawn
#

nothing about the timer should be resource intensive, is it perhaps just the material switching colors/enabling&disabling the light?

rich adder
#

yeah might be something with material maybe

high summit
#

I thought that but disabling the material section it still happens

#

it's the switching on/off of the light thats causing it

naive pawn
#

does fps drop when the switch happens, or is it just a consistent low fps?

high summit
slender nymph
#

have you profiled it?

high summit
#

but the fps counter drops alot

naive pawn
#

use the profiler to answer

high summit
#

Does seem to be a large hit when it's enabled

naive pawn
#

it may be due to the lighting/rendering involved with enabling the light

high summit
#

You'd expect the fps to rise after though right?

#

This is me on the other side of the map, enabling/disabling the flash script

#

The light has a small range of 5

slender nymph
#

what does the profiler say is taking the most time

high summit
#

Actually, editor loop?

#

I think I figured it out

#

It's lagging because I have it selected, showing the properties panel of that light makes the fps drop

#

Strange to drop so much, Potentially the fast moving timer variable on the screen

cosmic quail
orchid trout
#

Question about coroutines in unity/game development.
I see a lot of posts about them saying "They're good/okay to use, but often get misused/overused." but without clarification.

What is the correct use case moment for using a coroutine? How/when/what should it be used for, and NOT used for?

rich adder
#

when you need a faux async function that runs on the main thread donkeyKongThumbsUp

thorn stone
#

I am back

#

And I removed everything

#

Did everything again

#

And mid way realised that I didnt apply script into player

#

👍

ashen wind
#

hey i'm noticing that my sprites get blurry when they move across the screen. is there a setting to prevent this kind of thing?

ashen wind
#

settings can be changed in code

rich adder
#

that doesnt make this a code question

cosmic quail
ashen wind
#

if you don't know the answer, why are you responding?

rich adder
#

this isn't one of them

ashen wind
#

ok, then point me to the appropriate channel

rich adder
#

read the descriptions they mean stuff

frail hawk
eternal needle
# orchid trout Question about coroutines in unity/game development. I see a lot of posts about ...

overuse would imply youre using one for no reason, when the logic could've easily been thrown in update. Starting a coroutine allocates memory so that's one thing they could be referring to.
Any problem you can solve in a coroutine can be solved in update (from my experience) although sometimes its easier to write it in a coroutine. Like let's say you want an object to change color. This only happens after a method is called after a 5 second delay. In update, you'd have to check a bool to see if the method was called, then check if its been 5 seconds. It's not complex code by any means but compare to in a coroutine, its 1 line to wait 5 seconds. You dont need to check if the method was called since you'd be calling start coroutine already

rapid laurel
#

when i build my game my first canvas doesnt match the screen size, but it does on unity anyone can help? its just the canvas of the principal menu

frail hawk
rapid laurel
#

ty

timber tide
brave robin
#

The other issue with nesting coroutines is that there's always a 1 frame delay before a yield start coroutine begins, so lots of nesting will result in a noticeable delay to the player

scarlet skiff
#

are there any shortcuts or anything specifics to keep in mind when making an algorithm for path finding in a 2d game inside maps that use tiles and such

#

or any tutorials that you have found to be especially brilliant

slender nymph
#

the shortcut would be to use an asset that already did it for you. you just need the A* algorithm and there are plenty of implementations available for that to choose from

scarlet skiff
west garnet
#

im trying to make some kind of gambling for testing my skills, i did this code alone, how can i make the player input to analyse it on the code? do i just add a public player input on the code create it in the scene and then intead of the int that i have for the player i use player input?

using UnityEngine;
using TMPro;

public class Gambling : MonoBehaviour
{
    public int numberChoosen;

    public bool getSecretItem = false;
    private int randomNumber;

    

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.L))    
        {
            Gamble();
        }

        
    }

    public void Gamble()
    {
        randomNumber = Random.Range(1, 10);
        Debug.Log("The number that was rolled was:" + randomNumber);
        Debug.Log("The numer that you choose was:" + numberChoosen);

        if (randomNumber == numberChoosen)
        {
            getSecretItem = true;
            Debug.Log("You rolled the same number");
        }
        else
        {
            Debug.Log("Unlucky....You rolled the different number");
        }
        
    }
}
slender nymph
scarlet skiff
versed light
north kiln
dawn hound
#

If I'm running a bunch of calculations on start, would it be faster to just let the software freeze while it processes that or to split that calculating into steps with a coroutine and a calculated delay between steps?

#

I'm talking about while debugging not Release, of course

north kiln
#

It's faster to not add delays lol

dawn hound
#

Sure okay but then the software freezes for quite a while with no updates, logs, anything to tell you progress is being made as everything in start is trying to run in one frame

eternal needle
drifting cosmos
#

im learning from a unity microgame and theres an enemy prefab that doesn't have a health component attached to it but in an event it sets the enemys health to enemy.GetComponent<Health>(); and i asked ai and it says that shouldnt be possible

rocky gale
#

Yea it shouldn’t

drifting cosmos
#

its an official unity thing though and it works

rocky gale
#

There’s no script in the enemy called Health?

keen owl
#

i'm somewhat confused as to why this occurs, as it's quite unusual. I'm using a StateMachineBehaviour on an enemy and when the enemy dies (destroyed from the scene), I get this error:

"The object of type 'UnityEngine.Transform' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object."

quite strange because i've applied null checks everywhere in the script for attackObj but it always throws the error on this specific line:

if (attackObj != null) { attackObj.SetActive(true); }

the object itself is only being referenced in that script and nowhere externally, and it is not null on awake either. anyone have a clue why? is this an editor glitch or what?

rocky gale
#

That’s interesting

drifting cosmos
#

no its just one script

rocky gale
#

Can you send script that has the enemy.GetComponent<Health>()

drifting cosmos
#
public class PlayerEnemyCollision : Simulation.Event<PlayerEnemyCollision>
    {
        public EnemyController enemy;
        public PlayerController player;

        PlatformerModel model = Simulation.GetModel<PlatformerModel>();

        public override void Execute()
        {
            var willHurtEnemy = player.Bounds.center.y >= enemy.Bounds.max.y;

            if (willHurtEnemy)
            {
                var enemyHealth = enemy.GetComponent<Health>();
                if (enemyHealth != null)
                {
                    enemyHealth.Decrement();
                    if (!enemyHealth.IsAlive)
                    {
                        Schedule<EnemyDeath>().enemy = enemy;
                        player.Bounce(2);
                    }
                    else
                    {
                        player.Bounce(7);
                    }
                }
                else
                {
                    Schedule<EnemyDeath>().enemy = enemy;
                    player.Bounce(2);
                }
            }
            else
            {
                Schedule<PlayerDeath>();
            }
        }
    }
}
#

!code

eternal falconBOT
rocky gale
#

Can you send EnemyController script

drifting cosmos
#

im not sure how to send code ill delete after

rocky gale
#

Ye it’s fine

drifting cosmos
#
namespace Platformer.Mechanics
{
    /// <summary>
    /// A simple controller for enemies. Provides movement control over a patrol path.
    /// </summary>
    [RequireComponent(typeof(AnimationController), typeof(Collider2D))]
    public class EnemyController : MonoBehaviour
    {
        public PatrolPath path;
        public AudioClip ouch;

        internal PatrolPath.Mover mover;
        internal AnimationController control;
        internal Collider2D _collider;
        internal AudioSource _audio;
        SpriteRenderer spriteRenderer;

        public Bounds Bounds => _collider.bounds;

        void Awake()
        {
            control = GetComponent<AnimationController>();
            _collider = GetComponent<Collider2D>();
            _audio = GetComponent<AudioSource>();
            spriteRenderer = GetComponent<SpriteRenderer>();
        }

        void OnCollisionEnter2D(Collision2D collision)
        {
            var player = collision.gameObject.GetComponent<PlayerController>();
            if (player != null)
            {
                var ev = Schedule<PlayerEnemyCollision>();
                ev.player = player;
                ev.enemy = this;
            }
        }

        void Update()
        {
            if (path != null)
            {
                if (mover == null) mover = path.CreateMover(control.maxSpeed * 0.5f);
                control.move.x = Mathf.Clamp(mover.Position.x - transform.position.x, -1, 1);
            }
        }

    }
}
dawn hound
rocky gale
drifting cosmos
#

i dont think so

rocky gale
#

That’s weird

drifting cosmos
#

its not something i should know though right

rocky gale
#

Idk I’m just confused based on what you’re telling me

#

I would think the EnemyController would have a Health script connected to it or something

#

Or a child

#

But it doesn’t seem like it

drifting cosmos
#

this wouldnt mean it has a child right

rocky gale
#

If you open the prefab you can see

eternal needle
# dawn hound I suppose my issue is that I don't understand how optimization works or how to m...

you can totally split it up if you want but that isnt an optimization. you'll just have a few frames run inbetween all the freezing.
if you're trying to optimize your code, then use the profiler and see whats specifically being slow. if this is just a ton of processing that cant reasonably be optimized then really just add a loading screen and ignore it. Depending on what you're doing, maybe using the job system or async if you know how those work

drifting cosmos
rocky gale
#

Honestly idk

#

That’s weird

slender nymph
drifting cosmos
slender nymph
#

okay and did you bother reading the code?

drifting cosmos
slender nymph
#

Okay so what does it do when it does not find a Health component on the enemy object?

drifting cosmos
#

from what i know it does find a health component

slender nymph
#

how have you confirmed that

#

because guess what: it doesn't.

drifting cosmos
#

the game is working and the code is working so i dont know when you jump on the enemy it kills it when you run into it kills you

slender nymph
#

again, read the code. tell me what it does when it does not find a Health component. don't debug using vibes, read the actual code

twin pivot
#

I need your !code as well

eternal falconBOT
onyx geyser
#

how do i even get this from doing nothing

#

it worked before, and now it doesn't

#

how

#

what happened

slender nymph
#

check your spelling. but if that isn't enough then you need to actually show the code instead of spamming a single thought across 5 messages

twin pivot
onyx geyser
slender nymph
#

start by configuring your !IDE 👇

eternal falconBOT
onyx geyser
#

is it really just.. that it needed an update

drifting cosmos
onyx geyser
#

I think it was unity freaking out, before I even did anything with the program it was having errors

drifting cosmos
onyx geyser
#

Yeah no that had no change, I tried it

#

It actually worked WITH the capitalization before

#

But then after I finished play, it started having a stroke

#

No, you don't get to doubt me, that's a singular line of code that I checked over multiple times

slender nymph
#

that is exactly the issue though

onyx geyser
#

It's having a stroke

slender nymph
#

which you would know if you had a configured IDE since it would be underlined in red

eternal needle
#

took me about 5 seconds to find the issue too. maybe check over it for another 20 minutes. or be sane and configure the IDE so the ide tells you exactly whats wrong

onyx geyser
#

What do yall think I'm doing

#

I'm telling yall it worked even with the capitalization getting screwed up, got told to go update the IDE, doing that

#

I don't know what else to say

slender nymph
#

if you changed it during play mode and you have the option to not compile changes until after exiting play mode then naturally it wouldn't have attempted to compile the incorrect code during play mode.

#

the current is is still the misspelling

onyx geyser
#

That'd make sense, if I made any changes in the first place

slender nymph
#

hint: you did

onyx geyser
slender nymph
#

incorrect code doesn't magically work, nor does the code magically change itself. you made a spelling mistake.

drifting cosmos
#

do you have to close your ide for your scripts to compile

slender nymph
#

no

frosty hound
#

No, you just have to save the script and Unity will compile next time you're in the editor.

onyx geyser
#

I'm not about to argue about it, normally I'd say yes, I made that mistake, but I also know I didn't make any changes to the line before, between, or after

#

So I don't know what to tell you