#💻┃code-beginner

1 messages · Page 465 of 1

hasty tundra
#

so long story short i cant set one dictionary to equal another?

ivory bobcat
#

Was that the only error?

willow scroll
hasty tundra
#

shoot yeah

#

wait im dumb#

willow scroll
#

It's telling you there is no implicit operator for this convention

short hazel
#

You have two WeaponDataType enums, considered different because they're stored inside separate classes

ivory bobcat
#

The keys of the two dictionaries aren't the same type

maiden chasm
#

Hey o need help hpw to setup an git where I can code with other peoples

cosmic dagger
#

use only one WeaponData type. there is no need for more than one . . .

hasty tundra
#

I have the Code Like This, But The Variable Displays Like This, How Do I Change The Values Of The Dictionary

wintry quarry
short hazel
#

Hm that code architecture doesn't smell good, what is this float array for? You should use a class if each denotes different "skill levels" as the dictionary name suggests, so each skill has an explicit name

short hazel
hasty tundra
#

the floats are simple values that are referenced, essentially if one value is a 1, another script would see it and change a value by that amount. The system works fully, as it should, but ive been trying to get the code more efficient and to make it saveable, which is how i was recommended dictionaries, and now ive gone down this rabbit hole 😭

short hazel
#

-# This also has the advantage where these names will be fully visible in the JSON file, making them easily editable by you or someone else

hasty tundra
short hazel
#

Using a separate, serializable class solves the issue

#

Unity's JsonUtility cannot serialize dictionaries, switch to a serializable class, or use a more potent JSON serializer like Newtonsoft.JSON

hasty tundra
#

im already using newtonsoft

short hazel
#

Then something else is going on, the variable used to save the skills stays null, so it writes null in the JSON

#

Make sure you copy its value before serializing

hasty tundra
#

i am i think, the save system i have implemented works well for every data type, arrays, bools, whatever, js not for dictionaries aparently

short hazel
#

Show the class that is used in the serializer, which contain all these properties

#

Newtonsoft does know how to handle dictionaries

hasty tundra
#
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;

public class ManageSkillTree : MonoBehaviour
{
    public enum WeaponDataType
    {
        Gun,
        Sniper,
        Minigun,
        Buckshot,
        Grenade
    }
    public Dictionary<WeaponDataType, float[]> Skills;

    private void Start()
    {
        Save();
        Load();
    }

    public void Load()
    {
        if (File.Exists(Application.dataPath + "/skills.txt"))
        {
            string saveString = File.ReadAllText(Application.dataPath + "/skills.txt");
            SkillData saveData = JsonConvert.DeserializeObject<SkillData>(saveString);
            Skills = saveData.SavedSkills;
            Debug.Log("Loaded");
        }
        else
        {
            Debug.Log("No File Found");
        }
    }

    public void Save()
    {
        SkillData saveData = new()
        {
            SavedSkills = Skills
        };
        string json = JsonConvert.SerializeObject(saveData);
        Debug.Log(json);
        File.WriteAllText(Application.dataPath + "/skills.txt", json);
        Debug.Log("Saved Skills");
    }
}

[System.Serializable]
class SkillData
{

    public Dictionary<ManageSkillTree.WeaponDataType, float[]> SavedSkills;

}
#

thats the script, its worked for everything except for the dictionary

short hazel
#

Yep SavedSkills isn't a property so it will most likely go right over it

#

You need to add accessors: { get; set; } to your variable, do you have that for the other ones?

#

as in: public Dictionary<ManageSkillTree.WeaponDataType, float[]> SavedSkills { get; set; }

#

If I remember correctly Newtonsoft won't look at fields unless you modify its configuration

hasty tundra
#

do i need that for the Skills dictionary aswell?

short hazel
#

Just inside SkillData

hasty tundra
#

ok

hasty tundra
short hazel
#

Okay, now that I've seen the code which saves and loads, post the code that inserts values into the dictionary

#

It's marked public in ManageSkillTree so I assume it's populated from somewhere else (another script?)

hasty tundra
#

it will be yeah, but for the minute im just trying to have the arays be shown as all 0s, so im working on it in the same script. The issue im having is not knowing how to assign values to specific arrays in the dictionary

#

like say i wanted to make Gun[1] = 0, idk how id do that

short hazel
#

Okay so since you don't actually use the dictionary, it won't have a value at all, hence why it's serializing null.
The variable can contain a dictionary, but that's not the case, since you haven't created one and put it into the variable yet

hasty tundra
#

i guessed as much yeah

short hazel
#

You need to initialize it yourself in void Start() before saving it

cosmic dagger
#

By default, the values of the float[] are 0, but if you're not using the dictionary, it will be null . . .

hasty tundra
#

im realising how little i know abt dictionaries rn, havent touched them in years

short hazel
#

Like any other class, with new

#

They're not different from other stuff, it's just that Unity makes it easy by populating most variables for you automatically, when you add a script to a game object

#

Dictionaries aren't one of the supported types, so you need to do it yourself

#

= new Dictionary<WeaponType, float[]>(), then you can add each of your entries to it

hasty tundra
#

ok well my last question is how to add the entries to it

#

then i think

#

i shd be set

short hazel
#

Docs will always have examples for the "common" stuff. Since Dictionary is a base C# thing, the documentation is on Microsoft's side

hasty tundra
#

i just realised that doing all of this doesnt even resolve the issue i was having to begin w lmao

#

but its all working now which is a +

burnt vapor
#

TL;DR, maybe this was already mentioned

rocky canyon
#

i built a great save/load system last year.. and i thought it was perfect..

#

it uses JSONUtility..

#

i keep feeling like maybe i should re-do it.. but idk

#

(everytime i hear soemthing like what Fused just said)

burnt vapor
#

You'd be surprised by how many things it can't serialize

#

Dictionaries, Lists (I think?), nullable types, root objects

rocky canyon
#

all i used it for was ints.. all my stuff is indexed

#

soo it works. so i probably should just leave it. until next one i build

burnt vapor
#

And instead of throwing an error, it just returns null or an empty object, I forgot which one

#

Things like that require workarounds or different types which just bloats code compared to Netwonsoft which is actually capable of doing it

#

Not to mention Newtonsoft is a mere package download away from being usable 😄

#

I will never stop recommending against JSONUtility

short hazel
#

Check the size of these objects (they might be too large, one may get in front of another and "steal" the click event), and that the method you've linked in the Event Trigger for each one of them is correct

topaz ice
#

Okay literally how do I fix that.

short hazel
#

You have that and UnityEngine.UI, and both have a Image, Button, etc. so your compiler can't guess which one you want to use, so these errors are reported

fossil tree
short hazel
#

Probably because the text also has a collider

cosmic dagger
short hazel
topaz ice
fossil tree
#

and i patch the problem

short hazel
#

UI Events use raycasts to dispatch them

fossil tree
#

yes but i cant change it

grave fog
#

can somebody help me out with a problem i have within a game, i cant get it to work. it has to do with a flashlight i want to be turned automaticly off for a jumpscare but i cant get it to work

rocky canyon
#

@grave fog you'll have to be a bit more specific

grave fog
#

yeah can i dm you about it ?

rocky canyon
#

whats happening. what should be happening... what u have (code-wise) !code this is how u share it 👇

eternal falconBOT
rocky canyon
#

just take ur time and write out a good descriptive question.. w/ context

grave fog
#

so i have these scripts. i want a script where if you go into box collider trigger 1 (variable) the light turns off and cant be turned off or on, then when you hit box collider trigger 2 the light can be turned back on and off thats it. but i just gett a log where it says a box collider is triggerd but nothing happends

rocky canyon
#

what logs do you get in the console?

#

the scripts look okay at first glance

grave fog
#

Trigger entered
UnityEngine.Debug:Log (object)
TriggerScript:OnTriggerEnter (UnityEngine.Collider) (at Assets/Scripts/TriggerScript.cs:17)

short hazel
#

In the code you showed, no logs correspond to the message you got in the console: "Trigger entered" - are you looking at the right scripts?

#

I'm blind lol, the log you're getting comes from TriggerScript, line 17

rocky canyon
#

tbh its weird how u have ur triggers split up

short hazel
#

Looks like AI code to me
// Correctly set property

burnt vapor
eternal falconBOT
rocky canyon
#
using UnityEngine;

public class FlashlightController : MonoBehaviour
{
    [SerializeField]
    private GameObject flashlight;
    bool on = false;
    bool isEnabled = true;

    void Update() {
        if (isEnabled && Input.GetKeyUp(KeyCode.F))
        {
            ToggleFlashlight();
        }
    }

    public void ToggleFlashlight()
    {
        if (isEnabled)
        {
            flashlight.SetActive(!on);
            on = !on;
        }
    }

    public void DisableFlashlight(){
        isEnabled = false;
    }

    public void RestoreFlashlight(){
        isEnabled = true;
    }
}
``` flashlight could only be in control of the flashlight
#

and then ur triggers could just be on the actual triggers.. (referencing the flashlight controller)

#

flashlightRef.DisableFlashlight();

short hazel
burnt vapor
#

But yes, it might actually be. Seems like a paste site

grave fog
#

Yes ive got it from ai, but i just have a trigger for entering the room and a trigger for leaving the room but the intire time i just want the flashlight to just be disabled but the code seems logic but jus nothing happends lol

short hazel
#

That's the problem with AI code, it seems logic but it's very much convoluted for what it needs to do and full of inconsistencies

burnt vapor
#

Yeah so basically delete it and learn to do it yourself. Even the smallest pieces of AI code will just make it more complicated in the end

#

Not to mention nobody in here is going to be bothered to help you if you use AI for your code

short hazel
#

For example, two scripts affect IsFlashlightDisabled where, in this context, there should be only one

grave fog
#

Yeah i know but when i had 1 script also nothing happends but the code seemed super logic

rocky canyon
#

3 scripts there..

  • flashlight script
  • script for disabling it (put on a trigger collider object)
  • script for enabling it (also put on a trigger collider object)

detecting for player or something simple.. -> reference flashlight controller -> turn off/on
(most importantly make sure ur triggers are being triggered) after that its pretty simple

maiden chasm
short hazel
#

hm, that means yes or no? You have both "Yes" and "haven't" in the same sentence

maiden chasm
#

I have gut hub and a Projekt but I havent a remote

#

But I have git hub but hiw to setup

short hazel
#

Create an empty repository on Github, you will publish your code from your computer onto it

maiden chasm
#

I want piblic only my friends can see it ok

short hazel
#

You can set it to private and invite maximum 5 people, if I remember correctly
Public will be visible by everyone

dapper wharf
#

where is the help channel? if there is one

maiden chasm
#

Ok

rocky canyon
dapper wharf
#

oh ok

maiden chasm
#

The reposity is cteatet

dapper wharf
#

I need help with stupid texture

#

idk how to fix

rocky canyon
dapper wharf
#

anytime I use probuilder to detatch a face more of those appear

#

ok

rocky canyon
maiden chasm
rocky canyon
#

just pick ur poison

maiden chasm
#

But I cant go on my pc

short hazel
maiden chasm
#

I have git on my pc true

short hazel
#

Open a File Explorer to your Unity project, and add a file named .gitignore (the file has no name, gitignore is the extension of the file). It should be put along the Assets, Library, Logs folders

steep rose
#

brackeys has a great tutorial for github with git

maiden chasm
short hazel
steep rose
#

what even is that

#

translator

short hazel
#

The most accurate one there is

steep rose
#

i have never seen that in my life

short hazel
#

It has a limited list of languages but it's very good at doing its job

maiden chasm
#

So I should renamr the folder name.gitignore

rocky canyon
#

Είσαι σίγουρος γι' αυτό;

maiden chasm
#

Sorry my Englisch is not the best englisch

steep rose
#

to the main repo

#

with all of your assets

#

and folders

maiden chasm
#

So the folder where everything is inside so the hyracy

#

And then

steep rose
#

if you are using github, please click add file then name it .gitignore

#

github should tell you if you are in the main or not

short hazel
#

You should have something like this:

rocky canyon
rocky canyon
steep rose
#

he is

#

it is impressive

maiden chasm
#

Can then I code with my friend

steep rose
#

does your friend know how to use git?

rocky canyon
#

Yet Another Test Project i feel that

maiden chasm
rocky canyon
#

language barrier is thicc up in here

steep rose
#

why did you send me a friend req?

short hazel
maiden chasm
rocky canyon
#

ding-dong ditch

steep rose
rocky canyon
#

i suggest finding you a guide/ tutorial / video or something.. in your language.. to learn all the stuff you need to know about github and version control

rocky canyon
#

reported

steep rose
#

ouch

maiden chasm
steep rose
#

where are you seeing this?

polar acorn
#

did you mean to type all this in a command line instead of discord

summer stump
#

what do this

Are you asking what this series of commands does? Each is easily googleable

atomic holly
#

Hello,
I don't understand why I have this error when I use Awake() but not when I use Start() :

NullReferenceException: Object reference not set to an instance of an object
GetCameraLimitation.Awake () (at Assets/Code/Scripts/Camera/GetCameraLimitation.cs:9)

My code :

using UnityEngine;

public class SetPlayerSpawn : MonoBehaviour
{
    private void Awake()
    {
        SingletonManager.instance.playerSpawn = this.transform.position;
    }
}
rich adder
rocky canyon
#

race condition

atomic holly
rich adder
#

Awake - Initialize
Start - Use Whatever

cosmic dagger
wintry quarry
rocky canyon
atomic holly
#

I give the collider to the variable in the singletonManager and after, with an OnSceneLoaded, I get the collider

spiral oak
rich adder
#

it knows what it is, it just doesnt know which one you want 😛

rocky canyon
rich adder
atomic holly
wintry quarry
cosmic dagger
atomic holly
#

In my other script, I have this :

using Cinemachine;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SetCameraLimitation : MonoBehaviour
{
    private PolygonCollider2D cameraLimitation;
    [SerializeField] private CinemachineConfiner2D confiner2D;

    private void OnEnable()
    {
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        cameraLimitation = SingletonManager.instance.cameraLimitation;
        confiner2D.m_BoundingShape2D = cameraLimitation;
    }

    private void OnDisable()
    {
        SceneManager.sceneLoaded -= OnSceneLoaded;
    }
}
rich adder
atomic holly
rich adder
#

but probably in this scene right , its not setup in a previous scene?

atomic holly
#

The thing I don't understand is even if I have this error, the variable is get in the other script

rich adder
#

is get?

#

. You can expect to receive the sceneLoaded notification after OnEnable but before Start for all objects in the scene
I think its running SceneLoaded before you assign it in that scene

atomic holly
#

Okay I got it
The error become at the previous scene when I set up all gameobjects to the DDOL. So, at this moment, the variable is not already setting so I have this error. But, when I change of scene, it works

rich adder
#

yeah I'm guess, likely cause its running SceneLoaded

#

maybe instead "ActiveSceneChanged" may not run on the first scene

atomic holly
#

Is there a way to don't use Awake at a specific scene ?

#

0r, is it not a problem to have this error ?

rich adder
#

you are confusing me a bit now lol
DDOLs dont run awake each scene btw, just once

#

are you talking about a different script now

rich adder
rich adder
#

if(scene.name == "mySceneName")
return;
//rest of code

atomic holly
bleak dune
#

Hi there im newish to unity jsut play around as much as i can why i wait for my other dev to do stuff ive come up with a idea for my game and wanted to know if there is any thing i need to install to make steam dlc work with my game so if i download one dlc and then get another dlc the game would pick up what i got and turn them both on at the same time. I hope someone can understand what i mean as i am dislexic and find it hard to say what i mean

crimson saffron
#

anyone know a good enemy AI tutorial out there?

rich adder
#

"enemy ai" is very vague

crimson saffron
#

idk just something to follow the player, i dont want anything too fancy

#

something modular to get me started

rich adder
#

learn how to make a basic FSM (finite state machine)

#

you can make an easy one using enums, not really modular but you'd only need a few states.
(idle, patrol, chase, etc.)

languid spire
eternal falconBOT
#

:teacher: Unity Learn ↗

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

fervent abyss
#
for (int i = 0; i < allowedApps.Length; i++)
        {
            byte count = (byte)i;
            spawnedApps[i].GetComponentInChildren<SystemUIButton>().onButtonClicked.AddListener(delegate
            {
                ComputerManager.instance.OpenApp(allowedApps[count]);
            });
        }

do u think its gonna be good performance creating byte in a loop (i do so for subscribing the event)

languid spire
polar acorn
fervent abyss
languid spire
fervent abyss
summer stump
languid spire
#

yes creating a variable is what you do anyway and the type makes no difference

summer stump
# fervent abyss both <3

You can't. It is always gonna be tradeoffs. You are trading memory cost for cpu cost, which is almost always bad

languid spire
#

'especially on a 64 bit cpu

fervent abyss
#

true

polar acorn
# fervent abyss both <3

Okay, please give your parameters for maximum time complexity and space complexity, and the weighting by which you value both. Then you can run a minimax algorithm to find the point at which the sum of the weighted values of complexity add to the smallest amount

#

Or

#

you can just use int and stop caring

fervent abyss
#

yeah i js turned my brain on

#

memory cheaper than cpu

uncut shoal
#

I'm trying to set the position of a UI element to the mouse, but it doesn't seem to work?

Vector2 position = Input.mousePosition;
elementEditor.transform.position = position;
```giving me a location like 28k, 29k, -4k
polar acorn
#

Input.mousePosition is in pixels on your screen

languid spire
polar acorn
#

You're probably going to want to find the world position of what your mouse is hovering over.

uncut shoal
#

o right

#

its not a normal transform

polar acorn
uncut shoal
#

I'm moving a UI element

#

SteveSmith answered the question

#

Thanks though, any help is fun

crimson saffron
#

how would i instantiate a particle system where a raycast hits?

strong wren
#

what should i rather use for my movement the rigidbody or character controller?

steep rose
steep rose
# strong wren what should i rather use for my movement the rigidbody or character controller?

it depends on what game you are making and what you are confortable with, if you are making a physics based game then i would go with rigidbody, if you are making a game with precise movements it would be good to go with character controller, rigidbody can make precise movements but you would need to configure it a lot, rigidbodies are also way easier to code since they are within unitys physics system, character controllers are really hard to make since you have to code everything from scratch including Gravity, Drag, Momentum, etc especially if you want a physics based character controller. the upside to a character controller is you can make very precise movements to suite your game.

strong wren
#

i already have to remake the player movement now i have to do these too?

uncut shoal
#

They're all quite easy

#

don't worry

steep rose
#

do what? im just telling you what you asked

#

the upsides and the downsides

strong wren
#

i already had the most basic but good movement system but cause it ignores colliders i have to redo it

strong wren
uncut shoal
#

I have a method that deletes a button when the left click button is clicked

#

in the LateUpdate method

#

But now every time I click the button, it deletes before it clicks

#

😭

steep rose
#

thats to be expected

uncut shoal
#

How do I make the method detect if the button was pressed instead of an element

strong wren
summer stump
#

What kind of button do you mean?

Hmm, what does "instead of an element" mean?

uncut shoal
#

A UI button, and the method is for moving around SpriteRenderer game objects with click and drag

steep rose
#

btw

strong wren
uncut shoal
# summer stump Ok, then OnClick

I heard OnClick doesn't work very well with Z so I made my own click detection by checking the mouse position and rect of the sprite

strong wren
#

cause instead of moving the object it teleports it

uncut shoal
#

to be able to have control over how it gets the sprite

#

since sometimes the objects can be over each other

#

how do I detect if there was a button clicked in the current frame?

#

Do I just loop through all buttons and check if the mouse is over them?

steep rose
strong wren
#

maybe i dont have to change alot since most of it is the same, like jumping is already in place all i have to do is tell it how to do the jumping

uncut shoal
#

how to check if a button is highlighted?

#

uhh it seems to be a protected method?

strong wren
#

uhm so when i press play my player just gets pushed with alot of force

#
        HorizontalInput = Input.GetAxis("Horizontal");

        Vector3 move = transform.right * transform.position.x + transform.forward * transform.position.z;

        CC.Move(move * Speed * Time.deltaTime);``` this is its movement code
#

its not rlly that hard but what would cause it to be launched when im not rlly touching the input buttons

mint remnant
#

dosn't look like your using them Input variables at all there

strong wren
#

i have no clue what im doing im just watching brackeys

#

wait i think i found the issue

#

x and z are varibles 🤦‍♂️

#

i should be using forward input and horizontal input

mint remnant
#

sometiems when watching tutorials, you have to pause and rewind alot to make sure you didn't miss the tiniest thing

strong wren
#

yep

#

well its not my fault my mom drank when she had me

uncut shoal
#

So is there any way to check if a button is highlighted...?

strong wren
#

isnt what im doing bad tho? wasnt there a golden rule to never follow tutorials cause then u fall in the pit where u ALWAYS need tutorials

strong wren
#

void OnMouseOver()

mint remnant
strong wren
#

omg the collisions 😩 i can actually run in the game without going thru stuff

strong wren
#

i mean its pretty easy to remember ig

uncut shoal
strong wren
#

i mostly write all the code myself so i guess watching 1 tut that easy to remeber wont kill me

strong wren
uncut shoal
#

I only really watched a few tutorials at the start and now mostly just google stuff

strong wren
#

but dont ask me for help i drank white paint instead of milk

uncut shoal
rocky canyon
#

magic isnt real 🪄

strong wren
#

u can check thru code 🤷‍♂️

#

dont u have like an UI controller?

rocky canyon
#

but yea.. if its highlighted its hovered..

#

chck if its hovered

strong wren
uncut shoal
strong wren
uncut shoal
#

Yea I do

strong wren
#

yeah then why not use it

rocky canyon
#

pretty much..

uncut shoal
#

AAAA there's a method in the Button behaviour that lets me get if its highlighted

#

BUT THE METHOD IS PROTECTED

strong wren
#

i think u can do that by declaring ur buttons then in the OnMouseOver thing then check if the thingi ur hovering over is a that specific gameobject

strong wren
rocky canyon
#

you can use

using UnityEngine.EventSystems;
using UnityEngine.UI;

public class IsSelected : Selectable
{
    BaseEventData BaseEvent;
    public GameObject dot;

    void Update()
    {
        if (sHighlighted(BaseEvent) == true)
        {
            dot.SetActive(true);
        }
        else
        {
            dot.SetActive(false);
        }
    }
}```
#

yea you could use selectable i guess

strong wren
#

oh nvm

uncut shoal
rocky canyon
#

this is how i handle that type of stuf

#

ishovered, notIsHovered

final kestrel
#

Yeah I was gonna say that IPointerEnter interface

uncut shoal
#

Basically, I have a system of creating elements that are basically just images. I let the player move the elements around with the left click button. They can right click the elements to open a menu to modify an element, and if they try to move an element while in the menu, it closes. However, this makes it so every time a left click is detected, the menu is closed, so I can't really use the menu.

rocky canyon
#

well check if ur moving an element.. while in the menu. and then prevent it from closing

#

else.. close it

uncut shoal
#

due to how I check if there's an element to move, clicking the 'Rename' button would move the monitor element instead, so it will close the menu and never let me rename

#

which is the primary reason I'm trying to check if a button is highlighted

uncut shoal
rocky canyon
#

go thru and check out what they do

uncut shoal
#

👍 thanks

rocky canyon
#

theres drag ones too it seems

final kestrel
#

for the drag thing. I remember watching an inventory tutorial where you can drag and drop items. Maybe you can make up something from that as well.

uncut shoal
#

dragging and dropping is already done

#
public class ButtonHover : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    public bool isHovering;

    public void OnPointerEnter(PointerEventData eventData)
    {
        isHovering = true;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        isHovering = false;
    }
}
#

I'll use this

drowsy flare
#

I have a list instanced in my MainManager containing ItemInstance objects:
public List<ItemInstance> Inventory;
I can modify the contents of that ItemInstance with something like this:
MainManager.Instance.Inventory[i].owner = null;

Now I would like to work directly with a reference to this item, with something like this:
ItemInstance weapon;
weapon = MainManager.Instance.Inventory[i];
weapon.owner = owner;

But it seems like weapon doesn't really point to the object in the list.

Is it possible to do something like this? Did I just make a mistake, or is my logic wrong?

willow scroll
uncut shoal
#

👍

drowsy flare
willow scroll
drowsy flare
# willow scroll Please, show it
{
    public ItemData itemType;
    public bool inUse;
    public string owner;
    public int ammo;

    public ItemInstance(ItemData itemData)
    {
        itemType = itemData;
        inUse = false;
        owner = null;
        ammo = 0;
    }
}````
willow scroll
#

Maybe, you're misunderstanding something?

drowsy flare
willow scroll
willow scroll
drowsy flare
#

Oh, right

willow scroll
#

Not sure whether one can say that, I mean, one says 4th, 5th, 6th etc.

drowsy flare
#

So are you saying, that in my code above, weapon is storing the reference to Inventorys i ? Just like I want it to do?

languid spire
willow scroll
#

Since it's a class

drowsy flare
#

Great, I was afraid that I had some logic error trying to do this. This means that my logic is right, I just gotta find the reason that it's not working. Thanks a lot.

Ooor just to be sure, if I modify a value in weapon, there is nothing actually stored in it, but it's just a reference to the i item in the list which gets modified, right?

willow scroll
drowsy flare
#

I'm asking because it seems like weapon contains like an empty instance, instead of pointing to the item in my list

willow scroll
#

That's a more convenient and readable way to do it

#

Reference and value types are also the reason we can store Transform, which is a class, to then modify its Vector3 position, a struct, but cannot position, because only its value will be copied, and upon modification, the actual Transform's position won't be affected

drowsy flare
#

I think I'm following

willow scroll
final kestrel
#

Are you sure you got stuff in the list

willow scroll
#

If it's null, the reference won't be stored

drowsy flare
#

I'm gonna triple check

willow scroll
#

You a debugger and hover the list's value

#

That's what I usually do

drowsy flare
#

It seems from my debug that it should actually be working:
weapon.itemType.itemName: zapper

#

Okay, thanks for the reassurance guys, there is something else wrong with my stuff. Greatly appreciate your help!

#

Okay, the problem was never that the reference to the list didn't work - it worked all the time. The problem was that I instantiated the weapon in root level in my scene, instead of in the hand of my character.
If it wasn't for you guys, I would still be banging my head against the list 🙂

willow scroll
# drowsy flare Okay, the problem was never that the reference to the list didn't work - it work...

This happens with everyone, my case is quite bad. I'm wasting hours blaming Unity's and C# bugs, which ruin my code, to then find out how miserable and easy-to-find the mistake I've created was. I then make sure to remember it for the next time and try to patiently solve the encountered issues, but start thinking this one is definitely not my fault and blame everything but me instead, to then find out for the hundredth time that this issue was caused by something even more dumb than the previous ones.

strong wren
#

how can i detect collisions with a charater controller

drowsy flare
willow scroll
#

It's important to not overcomplicate things and it would have been much better if I was able to listen to my own advice.

drowsy flare
#

My game was actually working before i started refactoring everything ...

final kestrel
willow scroll
wraith phoenix
#

I fixed my last issue.
It was quite involved but thank you to those that helped.

#

A new issue:
I have an animation rotation (z) I'm looking to modify based on my right joystick transform.position (playerControls.Aim.ReadValue<Vector2>().x, playerControls..ReadValue<Vector2>().y).
Can anyone help me understand how to convert an X,Y coordinate to a corresponding rotation angle?

willow scroll
#

If you're only using one axis, you should exclude y and rotate your character on Vector3.up based on x

wraith phoenix
#

Ok. I'll give this a shot. Thank you @willow scroll

#

But I am using two axis, X.Y. but that goes to one axis on the rotation.
The game is a top down isometric

#

8 directional movement, so northeast has X,Y coordinates of (0.75,0.75)

dull sluice
#

hi

#

im a beginner which was creating a pong game to understand unty and c# but caame to a problem when i wanted to create the ai for the opponent would anyone be willing to help.

languid spire
#

!ask

eternal falconBOT
dull sluice
#

i tried step 1 ,step 2 and 3 dont even know what it means, step 4 ill try after step 2 or 3 and srry ill do step 5

summer stump
#

3 also would be clicking the link to learn more

languid spire
dull sluice
languid spire
#

definitely click on the link provided

dull sluice
languid spire
dull sluice
#

found something that says debug on the top left of the screen

languid spire
lunar kelp
#

hello i had this problem yesterday but i tried it but didnt work when i put my enemy script into my prefab it moves but my clones wont move what can i do?

lunar kelp
#

nope

polar acorn
#

Show the inspectors of the clones

lunar kelp
#

the script?

polar acorn
#

The whole object preferably, but with this script visible

lunar kelp
#

this is the script

polar acorn
#

I asked for the inspector

lunar kelp
#

whats the inspector

polar acorn
#

The window that is labeled "Inspector"

lunar kelp
#

ohh hold on

polar acorn
#

The object

polar acorn
lunar kelp
polar acorn
#

This doesn't have the script on it

lunar kelp
#

i know but the clones spawn through the script

polar acorn
#

Okay, so what's supposed to move them

lunar kelp
#

enemy script

polar acorn
#

what enemy script

languid spire
#

There are no scripts on that object so how do you expect it to move?

lunar kelp
#

the enemy script

polar acorn
#

Okay, and does the enemy script somehow affect objects it is not on

lunar kelp
#

yes it affects the movement and speed

polar acorn
#

How?

charred spoke
#

It could if he wrote it like a ecs system ☺️

polar acorn
#

What makes this script affect objects it is not on?

lunar kelp
#

i think the enemy and waypoints are the main parts of the movement of my objects

polar acorn
#

You still haven't answered me

charred spoke
#

Can you show the enemy script ?

polar acorn
languid spire
lunar kelp
polar acorn
lunar kelp
polar acorn
#

And, as we have discussed, it is not on the object you're expecting to move

#

so, how are you expecting it to move

lunar kelp
#

ok what am i supposed to do ?

polar acorn
#

Perhaps you should put the script that moves the object it is on, on the object you want to move

charred spoke
#

Add the Enemy component to your enemy prefab

lunar kelp
#

i did

polar acorn
#

No, you didn't

charred spoke
#

Not according to your screenshots

lunar kelp
polar acorn
#

You literally sent a screenshot proving you didn't

polar acorn
polar acorn
charred spoke
#

Did you apply the change to the actual prefab you are spawning ?

polar acorn
#

This one has the enemy script on it

short hazel
#

Nope

slender nymph
charred spoke
#

Show the prefab

slender nymph
#

that green + on the component's icon means it is an unapplied override 😉

short hazel
#

The blue margin and the green "+" icon shows that it was added later on, compared to the prefab

lunar kelp
#

im still confused

polar acorn
#

You have put the Enemy script on an object

#

but not the prefab

#

and therefore, not on the clones

lunar kelp
#

yeah but where do i put it on

polar acorn
#

the prefab

short hazel
#

When you drag-drop a prefab into the scene, it creates a copy of it. Any modifications you make on it won't be reflected to the prefab until you explicitly tell it to do so

charred spoke
#

The object in your scene is a i stance of the prefab

#

The actual prefab lives in your project folder where you saved it

lunar kelp
#

oh im so dumb

#

now it worked

buoyant goblet
#

Heyo, I made a spline using Unity's spline package, I was wondering how I can make a reference to the spline in my script? Normally for something like text I'd do TMP_Text, but using Spline seems to create an array, and does not allow me to drag the spline in inspector

charred spoke
#

You can apply the change from tue scene to the real prefab fron the override menu

lunar kelp
#

it was in a different folder so i didnt really know how to do them at the same time

buoyant goblet
slender nymph
slender nymph
#

dang i was just barely too slow lol

buoyant goblet
#

lol no worries! appreciated anyway to know for sure haha

mint remnant
lunar kelp
#

ok

magic quarry
#

if i just put a bunch of simple math with non-variable numbers in a C# script, like var x = 1 + 2 * 8 , i'm correct in assuming that unity will optimize that so it never actually re-calculates 17 during runtime?

slender nymph
magic quarry
#

fantastic, ty. it's just clearer to do it this way sometimes, when it's otherwise not obvious how you get the 'magic number'

cunning rapids
#

Hey guys, I have a problem with my weapon sway. I'm using a script that works perfectly fine. But it works better when the framerate is uncapped. My weapons sways significantly more when VSync is turned on

teal viper
cunning rapids
#

Indeed

teal viper
#

I'd also remind you that we can't read your thoughts and have a peek at your code without you sharing it.

cunning rapids
#

Math.SmoothDamp is framerate dependent, right?

teal viper
cunning rapids
teal viper
#

A code issue can't be solved without having the said code.

cunning rapids
#

I understand that, but I was more so looking for common problems and potential solutions, given the circumstances

#

However I'm guessing that it's still too vague to tell?

#

I've googled potentially other implementations but I've found to prefer mine

#

Just this one issue holding it back

#

It's late in my timezone, so I'll come back tomorrow

#

When I'm able to provide the script

teal viper
summer stump
cunning rapids
cunning rapids
#

Sometimes stupid questions slip out of me

#

Anyways, I'll go now

#

Thank you for trying to help anyway

summer stump
cunning rapids
#

Also true 🙏

sick storm
#

!code

eternal falconBOT
sick storm
#

Hi, i am trying to make it so my dash will work while i am grounded but when i am dashing airborn into the ground when i touch the ground the dash gets canceled can anyone help me

rich adder
sick storm
#

i want it to cancel when i hit the ground not when i am on the ground

#

ik w=that it cancels while im pon the ground

rich adder
#

huh so why did you put the code that way

sick storm
#

im just keeping it there to test what it is like

#

idk how i would make it so the game knows when i have hit the ground while dashing

rich adder
sick storm
#

here is the full script

#

i have an isjumping bool

#

but idk how i would use it to distinguish when i have touched the ground after being airborne

rich adder
#

or forget the bools and start making a simple fsm

quiet grail
sick storm
#

what is a fsm

rich adder
#

finite state machine

sick storm
#

for this fsm would i only have to include states when i am jumping, grounded, and landing?

rich adder
#

grounded can be bool

sick storm
#

alr

sick storm
#

thanks fsm's sound like very important for making games will implement it

rich adder
#

i would recommend also splitting your code up a bit instead of cramming it all in one file, have a script for dash feature , movement etc.

sour snow
#

how do i learn how to code

summer stump
eternal falconBOT
#

:teacher: Unity Learn ↗

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

rich adder
#

check pins

hallow sun
#

hi is there a way to get an enum's index? as in its position from the list, for example:

public enum Test { First, Second, Third }
public class Script : MonoBehaviour {
  public Test test;
  void Start() { int x = //test.id; }
}
slender nymph
#

cast it to int. just keep in mind that the values start at 0 (unless explicitly assigned), so Test.First in this case would be cast to 0

hallow sun
slender nymph
#

yep, exactly the same way

hallow sun
#

like this: (Test)integerVariable; ?

slender nymph
#

yep

rich adder
#

enum aka = exciting number

hallow sun
indigo mirage
#

Quick question, how do I use headers properly, my code looks like this

But in the debugger, its not showing the headers

rich adder
#

ur in debug mode, yeah that wont work

indigo mirage
#

How do i get out of debug mode?

rich adder
#

3 dots menu in inspector

indigo mirage
#

Ah , i got you, thanks

keen pecan
#

Does anyone know how to join games via P2P by using a generated code rather than IP address?

summer stump
keen pecan
#

lol not sure because its like beginner for multiplayer

teal viper
#

Multiplayer and beginner don't really go together well lol

keen pecan
#

Wasnt sure if that was for multiplayer or like job connections lol

tender hamlet
teal viper
tender hamlet
#

thats what i thought of doing but im not sure how, any guides?

teal viper
#

Also I recommend going over the beginner pathways on !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

tender hamlet
#

thanks

#

wait, is it possible to grab just the instantiate component from the gameobject and put it on another gameobject.

tender hamlet
#

okay, so in another part of my code i create a gameobject then add a spline container, but instead i think i should have this instantiate be created then add the spline container onto it. how would i identify the object i created? like before what i wrote was

GameObject ChainContainer = new GameObject(); //Creates game object named ChainContainer
        ChainContainer.name = "Chain Container"; //names object whatever is in Quotations
        ChainContainer.gameObject.transform.Translate(0, 0, 0);

and i could identify that part because i made its name, but what can i add to this Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity); to give it the same type of name

teal viper
#

You can check the documentation of Instantiate and what it returns.

topaz mortar
#

How do I prevent this error? Not sure why it even happens?
if (item.ItemData.Skills.Count > 0) throws a NullReferenceException on Skills.Count, I use item.ItemData in the line above and that works.
But it's defined like this: public List<int> Skills { get; set; } = new List<int>(); so it should be defined and the count should just be 0 not?

#
Debug.Log(item.ItemData.Skills);
Debug.Log(item.ItemData.Skills.Count);```
summer stump
topaz mortar
#

Well I know the issue, just not how to prevent it.
ItemData is being loaded from my server, which doesn't have Skills (yet)

#

but I thought by adding the = new List<int>(); part I would always prevent it from being null

#

guess that doesn't make sense 😛

#

What's a good way to deal with stuff like this?
I have characters with items on my server.
I added a new variable to items (Skills), but my existing items on the server don't have this variable yet, how do I prevent errors like this?

#

An easy fix is just:
if (item.ItemData.Skills != null && item.ItemData.Skills.Count > 0)
But not sure if that's a proper way to handle it?

ivory bobcat
#

To debug, remove the set and errors will be thrown for all attempts in accessing the collection through the set property.

#

If set is removed, you'll not be able to change/re-assign a new instance to the backing field via property and validate your claim that the field-property had definitely been initialized and not null.

mint imp
#

i have no clue why this isnt working

polar acorn
ivory bobcat
#

Keyword 'local function'

mint imp
#

i do?

#

i put it in the class

#

maybe i screwed up or something

polar acorn
#

Show full !code

eternal falconBOT
ivory bobcat
#

Move it outside of the other function scope

#

You've practically placed it inside another method.

mint imp
#

its not in the function scope anymore

#

i wasnt either

ivory bobcat
#

For instance:cs private void Update() { void OnCollisionEnter2D()//Local function { } }

polar acorn
eternal falconBOT
polar acorn
#

Both of those functions are inside another function

mint imp
#

can you like underline the function its in cuz i literally put it under the class, its not under any function

ivory bobcat
# mint imp

Don't post an image. Instead, copy your code onto a paste site (save) and paste the url here.

polar acorn
mint imp
#

ok

#

i didnt know you could do that

#

im just trying to get help

normal rose
#

can anyone like have guide or tell me how do i integrate voice recog

mint imp
#

how tf does this work

normal rose
#

even simple one will do

#

😔

polar acorn
#

Here it is a third time. !code

eternal falconBOT
mint imp
#

!code void OnCollisionEnter2D(Collision collision)
{
Debug.Log("ran collision");
if (collision.gameObject.tag == "Enemy")
{
canMove = false;
rb.AddForce(rb.velocity * 1000);
Debug.Log("Ran tag");
}
}

eternal falconBOT
mint imp
#

OMG

#

im so confused

polar acorn
#

read the bot message

mint imp
#

im sorry

polar acorn
#

It's a thing for you to read

mint imp
#

stop being so passive agressive

#

im trying to find my way

#

cs
void OnCollisionEnter2D(Collision collision)
{
Debug.Log("ran collision");
if (collision.gameObject.tag == "Enemy")
{
canMove = false;
rb.AddForce(rb.velocity * 1000);
Debug.Log("Ran tag");
}
}

#

cs void OnCollisionEnter2D(Collision collision)
{
Debug.Log("ran collision");
if (collision.gameObject.tag == "Enemy")
{
canMove = false;
rb.AddForce(rb.velocity * 1000);
Debug.Log("Ran tag");
}
}

ivory bobcat
eternal falconBOT
normal rose
#

ah ok

#

ty

mint imp
#

cs
void OnCollisionEnter2D(Collision collision)
{
Debug.Log("ran collision");
if (collision.gameObject.tag == "Enemy")
{
canMove = false;
rb.AddForce(rb.velocity * 1000);
Debug.Log("Ran tag");
}
}
//

polar acorn
#

read the bot

#

and post the full script

ivory bobcat
mint imp
#

I KNOW

#

im just confused

ivory bobcat
#

You need to use the links (paste/save) and post the url here.

mint imp
polar acorn
ivory bobcat
#

Dude the flking entire script..

polar acorn
#

actually think

#

we can tell what function this is inside of

#

with this

ivory bobcat
#

That method has no errors. You've simply place it inside another method.

mint imp
#

FUCKING HELL I'LL JUST LOOK IT UP

polar acorn
#

You already have the answer. Your function is inside another function

#

Since you're apparently unable to find out which function, you asked us to find it for you

#

and then refused to provide the script

mint imp
#

I DONT KNOW HOW THIS WORKS

polar acorn
#

I don't know what you're expecting at this point

mint imp
#

I am trying my best

#

im sorry

#

i dont know how this works

polar acorn
#

Just post the script

#

the full script

#

like we asked

mint imp
#

OHHH

#

is this good?

#

im so sorry i feel so fucking stupid right now

#

sorry for being such an asshole i get kinda emotional at night

polar acorn
ivory bobcat
#

Show an image of the console error from the Unity Editor

mint imp
#

yea

#

i pressed the save button

#

ok i will

ivory bobcat
#

Full stacktrace pls

mint imp
#

what is a stacktrace

polar acorn
# mint imp

this is a different script and a different error

ivory bobcat
#

That's not the unity editor. That's your ide.

mint imp
#

oh

ivory bobcat
#

The error was from PlayerGeneral.cs btw and not the one you posted unless the class name and script name explicitly do not match

mint imp
#

they dont

#

i changed the name and i didnt realize you could change the class name without screwing up the script

#

it used to be playermovement but then i wanted to use it for other stuff

polar acorn
# mint imp they dont

Okay. So it's the correct script, but this is a different error. You have the wrong parameter type for the function

ivory bobcat
#

Still waiting for the console log window and stacktrace to validate error

mint imp
#

wdym i used the autofill feature it cant be wrong

polar acorn
#

Look up OnCollisionEnter2D and see what parameters it takes, and compare them to yours

mint imp
#

and no warning or error

#

i've seen it

ivory bobcat
mint imp
#

it has an error but its an unrelated error

#

if you wanna see that i can show you

ivory bobcat
#

Nevermind, you had a warning about local function not being used.

mint imp
#

ok

ivory bobcat
#

It won't display

polar acorn
#

But VS extensions would detect the incorrect signature at compile time and give a warning

ivory bobcat
polar acorn
mint imp
#

im so sorry about all of this

#

yall were right it was the parameters

#

please forgive me for lashing out at yall

summer stump
mint imp
#

oh

#

didnt know that

topaz mortar
#

How would I debug an event not being called? As far as I can tell I set everything up the way I normally do, but my event is not getting called

topaz mortar
#

EventManager:

public static void StartAddSkillToItemEvent(Skill skill, Item item)
{
    Debug.Log("StartAddSkillToItemEvent");
    AddSkillToItem?.Invoke(skill, item);
}

Inventory:

{
    EventManager.AddSkillToItem += AddSkillToItem;
}

public void AddSkillToItem(Skill skill, Item item)
{
    Debug.Log("Adding skill: " + skill.ItemData.Id + " to item: " + item.ItemData.Id);
}```
"StartAddSkillToItemEvent" is shown in my console, but "Adding skill: ..." is not
eternal needle
topaz mortar
#

it's actually in the Inventory script too, so it should've called Start by then not?

eternal needle
#

🤷‍♂️ I dont see the code for it

#

Either its subscribed after you invoked the event, or you removed it from the event before invoking.

topaz mortar
eternal needle
#

That is subscribing to the event, not invoking the event

summer stump
topaz mortar
#

I invoke it in another function in my inventory script

#
EventManager.StartAddSkillToItemEvent(skill, item);```
#

and that log is showing too

keen dew
#

Just put another log in the Start and check so nobody needs to speculate

eternal needle
#

when is it being invoked, and yea do what Nitku said then show the logs

languid spire
#

Also log the unsubscribe

topaz mortar
#

Alright, so my Start function of the Inventory script is (no longer) being called, how does that happen?

languid spire
#

the script is not enabled

summer stump
#

Not relevant to the issue, but did you know about string interpolation?

Debug.Log($"Calling event to attach skill: {skill.ItemData.Id} to item: {item.ItemData.Id}"):

A bit easier than that concatenation

ivory bobcat
topaz mortar
#

Uff, yeah I have the GO the script is attached to set to disabled by default lol

#

thx 🙂

keen dew
#

and the important lesson here (again) is verify, don't assume

topaz mortar
#

So how/why is it possible to call a function of a script that is not "Started" yet?

#

and can I manually "start" my script while the GO is inactive?

languid spire
topaz mortar
#

yeah that makes sense

#

so I can move my event subscriptions to a custom function instead of Start and just call that where I need it?

topaz mortar
#

or is just calling Start ok too?

languid spire
#

just make sure to unsubscribe as well

wintry quarry
languid spire
wintry quarry
#

It will then run twice

topaz mortar
eternal needle
#

Typically I try not to use awake/start when unnecessary if I need a specific order to complicated things.

summer stump
# topaz mortar why? how?

When you enable it, it will run
If you called it already, that is two times

Oh, you were asking about unsubscibing. My bad

languid spire
topaz mortar
#

but my events need to stay subscribed as long as the game runs

#

I never destroy the script

languid spire
#

But Unity does

topaz mortar
#

eh? again when? how? why?

#

pretty sure it doesn't in my game

eternal needle
#

Is this object in the DDOL scene? Itll be destroyed when loading a new scene if not

topaz mortar
#

I never load new scenes

languid spire
summer stump
eternal needle
#

Well incase you end up doing so, it's good practice to also unsubscribe.

ivory bobcat
eternal needle
#

Sometimes I also just set the event to null if I know its no longer needed rather than unsubscribing everywhere. Like the death of a character for example

topaz mortar
#

but it make sense to unsubscribe as best practice in case I ever do add more scenes

summer stump
languid spire
topaz mortar
#

is unsubscribe just
EventManager.EquipEquippable -= EquipItem;
or do I need to look up how to do it?

languid spire
#

that is correct

#

it's just the oposite of subscribe

topaz mortar
#

I'll just add it to be sure then

languid spire
#

good plan

topaz mortar
loud sage
#

I have an issue with the configuration of a gameobject, that's an inspector thing so what's the proper place to ask?

topaz mortar
#

Sword is my Item
Health Orb is a Skill attached to that Item
Why does item.GetComponentsInChildren<Skill>() not work here?

loud sage
topaz mortar
#

Ew cuz it's inactive ofcourse 😭

craggy night
#

r there any difference between Update and FixedUpdate?

deft grail
#

fixed update is for the physics system

#

it runs at a different rate than Update

craggy night
#

thank u

opal zealot
#

Hmm, I'm planing on building a skill database for my RPG game but I'm not so sure where do I start. I never got this far before(since I'm too engrossed on making the char movement smooth and not buggy at all).

deft grail
opal zealot
#

Now u have decided to build skills into game ya

#

I get the idea of a skill system, but I'm not so sure about the specifics.

#

Like do I follow this tutorial for the skill system he mentioned?: https://youtu.be/V4WrS-Wt2xU?si=ZuE49l7vXX8Dlb6d&t=554

🚨 Wishlist Revolocity on Steam! https://store.steampowered.com/app/2762050/Revolocity/ 🚨 🎮 Speed up your game-dev workflow with Synty Studios packs! https://syntystore.com/45b3b

📁 Get access to my tutorial project files over on Patreon: https://www.patreon.com/danpos

Welcome to part one of a two part tutorial in which I will hopefully show you...

▶ Play video
wintry quarry
opal zealot
#

Like do I make a database out of each int function?

deft grail
wintry quarry
#

Some people use spreadsheets

#

Some use ScriptableObject

opal zealot
#

Ah

opal zealot
#

And do I dump it all into a VSCode script for good measure?

opal zealot
#

@deft grail Something like this for where all the Skill/Stat database would be stored in: https://hastebin.com/share/tubepodelu.java

deft grail
opal zealot
empty summit
#

I would like to render the game at a resolution of 320 x 240 pixels but make it possible for the window to be fullscreen.
How do you do it correctly? i made a view in the game window of this resolution but i can only use the scale to zoom

languid spire
wraith phoenix
#

I'm trying to rotate my attack animation to my crosshair controlled by the right joystick in a top-down isometric.

private void AxeAttackParameters() {

    aimInput = playerController.GetPlayerAimInput();

    Vector3 direction = new Vector3(aimInput.x, aimInput.y, 0).normalized;

    float angle = Mathf.Atan2(aimInput.y, aimInput.x) * Mathf.Rad2Deg;
    Quaternion rotation = Quaternion.Euler(0, 0, angle);

    // Instantiate the slash animation with calculated rotation
    slashAnim = Instantiate(slashAnimPrefab, crosshair.transform.position, rotation);
    slashAnim.transform.parent = crosshair.transform;
   
    myAnimator.SetTrigger("Axe Attack");  
}

So far no matter what I do, the animation fires in the same place.
The closest I got was changing the rotation.z and this worked in the editor but when the game was running the animation still appeared in the original position even though the instantiated game object had a modified z rotation.

Does anyone have some insight they can please share?

iron blade
#

anyone know whats the best way to fix the floating point inaccuracies when dealing with hit.normal?

currently when capsulecasting straight down, hit.normal is equal to (0,003f, 0.9996f, 0f)

ripe shard
iron blade
ripe shard
#

What are you trying to do that this even matters?

iron blade
#

non-rigidbody based character controller

ripe shard
#

I mean what specifically

#

Why do you need that accuracy

iron blade
#

i have a movement vector

#

and then im trying to project the movement vector onto a ramp

#

but when theres no ramp

#

it still detects it as having a ramp

#

when hit.normal is (~0,~1,~0)

ripe shard
#

if you have a concept of a ramp in your gamedesign you will have well defined metrics for the angles these can have. Otherwise you would not need to discriminate between ramp/flat ground

iron blade
#

hmm so i should just add like a threshold of ~0.001f

ripe shard
#

so you can either treat all ground the same, maybe with a max-incline detection, or you handle ramps discretely, which makes it safe to define your "padding" to deal with such inaccuracies

iron blade
#

im more worried about terrain ig

ripe shard
#

what does that mean?

#

you should treat terrain as a continuous surface not as bits that are perfectly flat and those that are > 0.001% non-flat

iron blade
#

the terrain that i sculpt

#

in unity

ripe shard
#

doesn't matter

#

maybe your problem is that you calculate a surface-aligned move-vector without also solving any collisions after

#

the collision solver would fix your clipping through the surface

iron blade
cunning rapids
#

Hello, I've actually come to this problem with my weapon sway yesterday but I wasn't able to send the script at the time so I wasn't able to get a concrete answer

#

The weapon sway works well but is framerate-dependent

#

When I turn on VSync, it sways much more than if I uncap the framerate

#
using UnityEngine;

public class WeaponSway : MonoBehaviour
{
    public float swayAmount = 0.1f;
    public float swaySpeed = 5.0f;
    public float moveAmount = 0.05f;
    public float moveSpeed = 2.0f;

    private Vector3 initialPosition;
    private Vector3 targetPosition;
    private Vector3 currentVelocity;

    void Start()
    {
        initialPosition = transform.localPosition;
    }

    void Update()
    {
        float swayX = Input.GetAxis("Mouse X") * swayAmount;
        float swayY = Input.GetAxis("Mouse Y") * swayAmount;
        targetPosition = initialPosition + new Vector3(swayX, swayY, 0);

        Vector3 playerMovement = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        Vector3 MovementSway = playerMovement * -moveAmount;
        targetPosition += MovementSway;

        transform.localPosition = Vector3.SmoothDamp(transform.localPosition, targetPosition, ref currentVelocity, 1f / swaySpeed);
    }
}
#

I don't know if this script is considered too large to send here directly

wraith phoenix
zinc shuttle
#

help, i want to recive a unity project via version control

#

friend sent me project but all i got an empty project

ivory bobcat
proper cloud
#

i have a death animation played by a animator. Now i want to play this on a trigger which works fine, but it seems i need a animation with the base sprite for everything that wants to use that explosion death which seems annoying to create (basicalli a new empty animation and a new animator for everything)
The image is the animator, and instead of "boxing around" i want a state that does nothing the animator can chill in

deft grail
#

if you right click the empty area you can create an empty state

proper cloud
#

and if i put nothing in it the base sprite will remain? damn, should have just tested it lul xd, thx for the answer

deft grail
round mirage
#

hello someone know what can i do for my player who noclip in wall when i run on him (the move script is in FixedUpdate()void FixedUpdate() { if (CanMove && loading.gameReady) { verticalInput = Input.GetAxis("Vertical"); horizontalInput = Input.GetAxis("Horizontal"); transform.Translate(Vector3.forward * verticalInput * speed * Time.deltaTime); transform.Translate(Vector3.right * horizontalInput * speed * Time.deltaTime); if (Input.GetKeyDown(KeyCode.Space) && isOnGround) { isOnGround = false; playerAnim.SetBool("isJumping", true); rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse); } } }

deft grail
#

you are just teleporting the player

round mirage
deft grail
round mirage
#

ok

round mirage
# deft grail rigidbody, or CC i think should work too

dont work 😦 void FixedUpdate() { if (CanMove && loading.gameReady) { verticalInput = Input.GetAxis("Vertical"); horizontalInput = Input.GetAxis("Horizontal"); rb.AddForce(Vector3.forward * verticalInput * speed * Time.deltaTime); rb.AddForce(Vector3.right * horizontalInput * speed * Time.deltaTime); if (Input.GetKeyDown(KeyCode.Space) && isOnGround) { isOnGround = false; playerAnim.SetBool("isJumping", true); rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse); } }

deft grail
round mirage
#

oh ye i forgot to delete

round mirage
# deft grail what doesnt work? also dont use `Time.deltaTime` with physics

dont work even if i delete Time.deltaTime void FixedUpdate() { if (CanMove && loading.gameReady) { verticalInput = Input.GetAxis("Vertical"); horizontalInput = Input.GetAxis("Horizontal"); rb.AddForce(Vector3.forward * verticalInput * speed); rb.AddForce(Vector3.right * horizontalInput * speed); if (Input.GetKeyDown(KeyCode.Space) && isOnGround) { isOnGround = false; playerAnim.SetBool("isJumping", true); rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse); } }

deft grail
#

what happens

round mirage
#

i cant move

deft grail
round mirage
#

ok

ionic zephyr
#

does anyone know a flood fill algorythm for this type of maps in which the empty spaces aren´t contained in the floor HashSet(in my case)?

round mirage
# deft grail think you need to combine into 1 vector and use only 1 add force, not sure exact...

like that (i cant move)``` if (CanMove && loading.gameReady)
{
verticalInput = Input.GetAxis("Vertical");
horizontalInput = Input.GetAxis("Horizontal");

    rb.AddForce(new Vector3(verticalInput, 0f, horizontalInput) * speed);
    if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
    {
        isOnGround = false;
        playerAnim.SetBool("isJumping", true);
        rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
    }
   }```
languid spire
languid spire
#

because it does not fire every frame and GetKeyDown is only valid for 1 frame

round mirage
#

ohhh ok

deft grail
# round mirage why ?

well your using GetAxis so its not AS bad.
but try doing GetKeyDown and you will see the problem

round mirage
deft grail
#

you can do any key

#

but ideally these days should be using the new input system

tender minnow
#

hi

deft grail
round mirage
deft grail
#

then its much easier to do different inputs for controllers and stuff

#

and easily change keybinds etc, and just manage the inputs that you have

round mirage
#

ok

tender minnow
frosty hound
#

!ban save 1209548762985402500 Racism

eternal falconBOT
#

dynoSuccess rando_rm was banned.

vocal wharf
#

what

mint remnant
upbeat snow
#

hey guys, I'm trying to slide in an character from the very right edge of the stage to the middle. I tried using a for loop below but it still seemed to be way too fast. I figured something was wrong and wonder anyone could help me spot the problem, or otherwise suggest another solution. Thx!

using System.Collections.Generic;
using UnityEngine;

public class momAttack : MonoBehaviour
{
    public float speed;

    void Update()
    {
        for(int i = 0; i < 100; i++)
        {
            transform.position += (Vector3.left * speed * Time.deltaTime);
        }
    }
}```
frosty hound
#

Remove the for loop entirely for starters

#

Update is called once per frame. If you move it 100 times in a single frame, it's going to be impossibly fast.

upbeat snow
#

oh wait i thought it does it for 100 frames lol

frosty hound
#

Nope

wintry quarry
upbeat snow
#

thx for the reminder! with that said, what should i do to say, move until it reaches a specific coordinate?

wintry quarry
#

Check if it has reached the coordinate

#

If not, keep moving it

mint remnant
#

add an if check to see if it's there if so break?

upbeat snow
#

but won't the if loop run in one frame as well?

wintry quarry
#

if is not a loop

#

I don't know what you mean by that

upbeat snow
#

oh srry

#

i meant like

#

isn't the if function going to act the same as the for loop, both completing in 1 update frame? I know it doesn't but what's the difference that causes the difference :/

wintry quarry
#

The difference is there is no loop

#

So the code will run one time per frame

upbeat snow
#

oH WAIT i get it

#

tyty

wintry quarry
#

A loop makes code run multiple times

upbeat snow
#

if will just run once per frame

#

thus acting different than the loop

#

which loops until it completes

#

dam i finally cleared the concept

wintry quarry
#

Well if will run as many times as you write it, like any other code. And if the if is inside a loop, it will run multiple times, because that's what loops do

#

this isn't a special property of an if statement

upbeat snow
#

yeah i understand now

#

tysm bro

frosty hound
#

@paper tangle Please don't crosspost.

ionic zephyr
echo ruin
languid spire
echo ruin
languid spire
echo ruin
#

Ah right

languid spire
#

good bit of lateral thinking though, shame it would never fly

thick swift
#

Does anyone know of a good tutorial on scene loading in vr, and displaying a logo during the fade?

mint remnant
pulsar forum
main quarry
#

So im doing a tutorial on how to use unity and such and im stuck on super simple stuff as i did everything he did but it just wont work and i cant find anything online. its simply teaching me about component's and its changing the color of a sprite,


(under void start section is the next part)

rend.color = newColor;```

everything works fine until i try and add the rend.color section of the code when i do that the sprite im trying to change the color of vanishes when i hit play. I know its not a big deal but i figured it would be best to get this out of the way now and figure out what's wrong for the future
polar acorn
#

You're likely making it transparent

main quarry
polar acorn
#

Check the color

#

Does it have 0 alpha

main quarry
#

whats the alpha?

#

(sorry im really new to all this)

polar acorn
mint remnant
#

the 4th color bar slider

polar acorn
#

It's just a general concept of color, it's not a Unity thing

main quarry
#

yeah that fixed it

round mirage
# deft grail its not "new", but if you go to the package manager you can import input system

hello i have tried this but i cant move again if (loading.gameReady) { if(CanMove) { if (Input.GetKeyDown(KeyCode.Space) && isOnGround) { isOnGround = false; playerAnim.SetBool("isJumping", true); rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse); } if (Input.GetKeyDown(KeyCode.W)) { rb.AddForce(Vector3.forward * speed); verticalInput = 1; } else if (Input.GetKeyDown(KeyCode.S)) { rb.AddForce(Vector3.back * speed); verticalInput = -1f; } else { verticalInput = 0; } if (Input.GetKeyDown(KeyCode.D)) { rb.AddForce(Vector3.right * speed); horizontalInput = 1; } else if (Input.GetKeyDown(KeyCode.Q)) { rb.AddForce(Vector3.left * speed); horizontalInput = -1f; } else { horizontalInput = 0; } }

mint remnant
#

Step 1, add some debug logs in there so you know where your code is trying to go vs. not

round mirage
#

oh ye ty 🙂

mint remnant
#

you'll have to post more of the code, it's not obvious if that is inside an Update call or not, if not them Input Gets probably won't trigger

short hazel
#

Last time it was in FixedUpdate. If that's still the case, they'll encounter massive issues with GetKeyDown desyncs

round mirage
mint remnant
#

rb.AddForce(Vector3.back * speed); looks suspicious, you don't really want speed in an add force call

languid spire
#

what do you do with horizontal and vertical input out side of this code

short hazel
round mirage
#

so what is the correct key for this ???

short hazel
#

GetKey(), which returns true for as long as you hold down the key

short hazel
#

For reference, GetKeyUp also exists, which triggers once, when you release the key

round mirage
short hazel
#

Are you moving the player with its transform anywhere else? In this script, or in another

round mirage
queen adder
#

is there a code to scroll to top of inspector via code?

mint remnant
#

unless this is just testing code you probably don't want to latch onto WASD keys, but prefer an abstracted layer like Vector3 moveDir = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;

queen adder
#

we have a method that moves a component to top of the inspector, would be nice if the scroll follows through

round mirage
mint remnant
round mirage
sterile wraith
#

Is update called before the frame is rendered?

round mirage
short hazel
#

Update runs before the frame is rendered according to the excution order

cosmic dagger
#

damn, too slow . . .

short hazel
#

Triple

rich adder
sterile wraith
#

ok sounds good

round mirage
verbal dome
#

Should use rigidbody.AddForce/velocity instead

round mirage
verbal dome
#

Rigidbody movement is not easy to get feeling right

#

What did you try though?

round mirage
#

if (Input.GetKey(KeyCode.W))
{
rb.addforce(vector3.forward * speed);
}
else if (Input.GetKey(KeyCode.S))
{
rb.addForce(vector3.back * speed);
)

round mirage
languid spire
steep rose
#

did you configure your !ide

eternal falconBOT
steep rose
#

it should tell you vector3 is wrong

round mirage
sleek gazelle
#
[RequireComponent(typeof(Animator))]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Animator))]
public class FadeAnimationScript : MonoBehaviour
{
    [SerializeField] Animator animator;
    [SerializeField] Image image;
    private static Color visible = new Color(1,1,1,1);

    void Start(){

    }

    void Update(){
        if (animator.GetCurrentAnimatorStateInfo(0).IsName("FadeOut"))
        {
            if(image.color.a == 0) gameObject.SetActive(false);
        }
        if (animator.GetCurrentAnimatorStateInfo(0).IsName("Idle"))
        {
            Debug.Log(1);
            image.color = visible;
        }
    }
}

I get in the console but my image's color is not being changed, can someone help me please? (even though the image it's assigned and not null)

steep rose
round mirage
steep rose
#

look up what issue means

languid spire
round mirage
steep rose
#

🤔