#💻┃code-beginner
1 messages · Page 465 of 1
Was that the only error?
Of course, you can. They have different types
It's telling you there is no implicit operator for this convention
You have two WeaponDataType enums, considered different because they're stored inside separate classes
The keys of the two dictionaries aren't the same type
Hey o need help hpw to setup an git where I can code with other peoples
use only one WeaponData type. there is no need for more than one . . .
I have the Code Like This, But The Variable Displays Like This, How Do I Change The Values Of The Dictionary
Use a serializable dictionary or use a different serializer
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
- Do you already have a Unity project locally on your computer?
- Do you already have a remote repository set up (like in GitHub, GitLab, etc.)?
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 😭
Yeah so these values buffs or debuffs other statistics, they're "multipliers". Better give them explicit names to them instead of remembering that "Recoil multiplier" is the third element of the array.
Which is more legible to someone that has never seen your code, Skills[MachineGun][2] or Skills[MachineGun].RecoilMultiplier?
-# 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
i get that yeah, but its not the issue i was having
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
im already using newtonsoft
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
i am i think, the save system i have implemented works well for every data type, arrays, bools, whatever, js not for dictionaries aparently
Show the class that is used in the serializer, which contain all these properties
Newtonsoft does know how to handle dictionaries
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
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
do i need that for the Skills dictionary aswell?
Just inside SkillData
ok
it is still saving as null
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?)
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
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
i guessed as much yeah
You need to initialize it yourself in void Start() before saving it
By default, the values of the float[] are 0, but if you're not using the dictionary, it will be null . . .
how wd i do that 😭
im realising how little i know abt dictionaries rn, havent touched them in years
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
ok well my last question is how to add the entries to it
then i think
i shd be set
See https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-a-dictionary-with-a-collection-initializer#example for different valid ways of doing it
Docs will always have examples for the "common" stuff. Since Dictionary is a base C# thing, the documentation is on Microsoft's side
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 +
JSONUtility is unable to serialize Dictionaries, just like a lot of other things. Consider using Newtonsoft which is actually capable of serializing these types
TL;DR, maybe this was already mentioned
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)
You'd be surprised by how many things it can't serialize
Dictionaries, Lists (I think?), nullable types, root objects
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
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
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
Okay literally how do I fix that.
Remove the using UnityEngine.UIElements directive at the top of the file
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
ok i understand why the objet is a parent of the text so the event are in the text too
Probably because the text also has a collider
what
Deselect the text as a raycast target . . .
I can't be any clearer than that
alr I'll re-read it a few times
that not raycast...
and i patch the problem
UI Events use raycasts to dispatch them
yes but i cant change it
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
@grave fog you'll have to be a bit more specific
yeah can i dm you about it ?
whats happening. what should be happening... what u have (code-wise) !code this is how u share it 👇
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
no, i dont accept dms sorry.. neither do most other users.. you can post here.. (+ that gives u the best chance on getting an answer from someone that knows)
just take ur time and write out a good descriptive question.. w/ context
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
Trigger entered
UnityEngine.Debug:Log (object)
TriggerScript:OnTriggerEnter (UnityEngine.Collider) (at Assets/Scripts/TriggerScript.cs:17)
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
tbh its weird how u have ur triggers split up
Looks like AI code to me
// Correctly set property
Hi, your editor is not configured. Please configure it first before solving your problem. !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
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();
This doesn't look like any IDE that I know, rather a screenshot of hastebin or whatever paste site (???)
Sharing a screenshot of the hastebin rather than sharing the actual hastebin would be something
But yes, it might actually be. Seems like a paste site
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
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
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
For example, two scripts affect IsFlashlightDisabled where, in this context, there should be only one
Yeah i know but when i had 1 script also nothing happends but the code seemed super logic
https://paste.myst.rs/dsohre7s heres how i'd do it
a powerful website for storing and sharing text and code snippets. completely free and open source.
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
Yes I havent an Gast hub remote
hm, that means yes or no? You have both "Yes" and "haven't" in the same sentence
I have gut hub and a Projekt but I havent a remote
But I have git hub but hiw to setup
Create an empty repository on Github, you will publish your code from your computer onto it
I want piblic only my friends can see it ok
You can set it to private and invite maximum 5 people, if I remember correctly
Public will be visible by everyone
where is the help channel? if there is one
Ok
everywhere
oh ok
The reposity is cteatet
#🔀┃art-asset-workflow if its not code related
orr. if its probuilder issue it could go in #💻┃unity-talk @dapper wharf
Here the link https://github.com/EPAXGAMINGtv/Extreme-games.git
just pick ur poison
But I cant go on my pc
Do you have Git installed on your computer? It's required to sync your changes between Github and your computer
I have git on my pc true
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
brackeys has a great tutorial for github with git
Gitarre the Explorer I must be name ....gitignore
Please use a translator, I have issues understanding what you mean here
https://www.deepl.com/translator
The most accurate one there is
i have never seen that in my life
It has a limited list of languages but it's very good at doing its job
So I should renamr the folder name.gitignore
Είσαι σίγουρος γι' αυτό;
Sorry my Englisch is not the best englisch
you add a file named .gitignore
to the main repo
with all of your assets
and folders
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
You should have something like this:
damn. ur fast
Can then I code with my friend
does your friend know how to use git?
Yet Another Test Project i feel that
I must be saying him
language barrier is thicc up in here
why did you send me a friend req?
And it's the one where there's more features than all the others I've got, ironically
Idk
ding-dong ditch
you are relaying this information to your friend?
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
i sent you a dm
reported
ouch
echo "# Extreme-games" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/EPAXGAMINGtv/Extreme-games.git
git push -u origin main
What do this
where are you seeing this?
what is the question here
did you mean to type all this in a command line instead of discord
what do this
Are you asking what this series of commands does? Each is easily googleable
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;
}
}
because you're probably assigning instance AFTER you try to use it
race condition
I don't understand
Awake - Initialize
Start - Use Whatever
if you assign instance in the Awake of SingletonManager then this script executes its Awake before the SingletonManager script assigns instance. as mentioned, it's called race conditions. if both assignments happen in Awake there is no way to tell which script will run first . . .
Start happens after instance is assigned so it works.
Awake is before, so it doesn't`

I give the collider to the variable in the singletonManager and after, with an OnSceneLoaded, I get the collider
You're telling "use my variable" to the program before telling it what your variable is
it knows what it is, it just doesnt know which one you want 😛
may want to restructure ur scripts.. or manually have one script run first.. using https://docs.unity3d.com/Manual/class-MonoManager.html
Okay but if I use Start, my variable in OnSceneLoaded don't get it
Sounds like a separate unrelated problem
where'd this come from?
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;
}
}
is SingletonManager.instance not in a DDOL ?
SingletonManager is in DDOL
but probably in this scene right , its not setup in a previous scene?
I set all gameobject in DDOL in a previous scene and after, load the first scene
The thing I don't understand is even if I have this error, the variable is get in the other script
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
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
yeah I'm guess, likely cause its running SceneLoaded
maybe instead "ActiveSceneChanged" may not run on the first scene
Is there a way to don't use Awake at a specific scene ?
0r, is it not a problem to have this error ?
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
No my bad, in OnSceneLoaded
you mean dont use OnSceneLoaded event in specific scene?
Yes
if(scene.name == "mySceneName")
return;
//rest of code
Nice. Thanks 👍
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
anyone know a good enemy AI tutorial out there?
"enemy ai" is very vague
idk just something to follow the player, i dont want anything too fancy
something modular to get me started
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.)
you may want to look at the AI Navigation tutorials on !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
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)
ok, thanks
why byte, the indexer will be taking an int
If you just want to avoid lambda capture, int count = i will work just fine
im js somehow hyperfixated on performance rn 💀
casting from int to byte and back to int is not performant in this case
but creating a variable is?
Do you want memory performance or cpu performance
Memory is cheap...
yes creating a variable is what you do anyway and the type makes no difference
both <3
You can't. It is always gonna be tradeoffs. You are trading memory cost for cpu cost, which is almost always bad
'especially on a 64 bit cpu
true
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
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
Input.mousePosition is in pixels on your screen
you might want to look at RectTransform
You're probably going to want to find the world position of what your mouse is hovering over.
I'm not moving a world element
I'm moving a UI element
SteveSmith answered the question
Thanks though, any help is fun
how would i instantiate a particle system where a raycast hits?
what should i rather use for my movement the rigidbody or character controller?
get the raycast hit position and spawn the particle system
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.
holy
i already have to remake the player movement now i have to do these too?
i already had the most basic but good movement system but cause it ignores colliders i have to redo it
alot more work
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
😭
a lot more work because you are using a character controller?
thats to be expected
How do I make the method detect if the button was pressed instead of an element
i mean im in like the finishing stages of the game now i have to redo the most important part so yeah
OnClick?
What kind of button do you mean?
Hmm, what does "instead of an element" mean?
A UI button, and the method is for moving around SpriteRenderer game objects with click and drag
both of those movement styles are personal preference
btw
Ok, then OnClick
i just know 2 ways of movement the rb.addforce which is janky and the transform.translate where people said to not use cause it ignores collisions alotâ
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
cause instead of moving the object it teleports it
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?
if you are using a character controller please use the move() or simplemove() method(s)
i mean im looking at a tutorial rn so yeah
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
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
dosn't look like your using them Input variables at all there
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
sometiems when watching tutorials, you have to pause and rewind alot to make sure you didn't miss the tiniest thing
So is there any way to check if a button is highlighted...?
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
isnt there a method to check if the mouse is over the specified thing
void OnMouseOver()
nothing wrong with watching tutorial videos, just keep in the back of your head to be learning and not wrote copying
omg the collisions 😩 i can actually run in the game without going thru stuff
oh ok
i mean its pretty easy to remember ig
I'd prefer if there was a way without having to create a new behaviour and put it on every button. There can't be no way to get it.
i mostly write all the code myself so i guess watching 1 tut that easy to remeber wont kill me
i dont think u can check if its highlighted, i think u can only check if the cursor is over it with code
I only really watched a few tutorials at the start and now mostly just google stuff
but dont ask me for help i drank white paint instead of milk
seems like that based on what I can find on google but I was hoping someone here could know a magical way
magic isnt real 🪄
so u tryna said what i said was actually true and useful?
A what exactly?
like an empty gameobject with a script that does most of the ui things
Yea I do
yeah then why not use it
pretty much..
AAAA there's a method in the Button behaviour that lets me get if its highlighted
BUT THE METHOD IS PROTECTED
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
dayum so iim not rlly a mistake overall
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
oh nvm
Problem is, that's not exactly what I'm trying to do.
Yeah I was gonna say that IPointerEnter interface
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.
well check if ur moving an element.. while in the menu. and then prevent it from closing
else.. close it
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
I'll try this ig
👍 thanks
theres drag ones too it seems
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.
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
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?
Make sure you also know about IPointerMoveHandler for continuous logic
👍
What is ItemInstance?
Oh, it's just a c class
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;
}
}````
The reference must be stored here
Maybe, you're misunderstanding something?
What do you mean by here?
class is a reference-type, so weapon must store the reference to the Intentory's ith item
ith?
The item with the index i
Oh, right
Not sure whether one can say that, I mean, one says 4th, 5th, 6th etc.
So are you saying, that in my code above, weapon is storing the reference to Inventorys i ? Just like I want it to do?
n'th
Yes, it must store it
Since it's a class
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?
I thought you were asking, because you were sure the reference isn't stored
I'm asking because it seems like weapon contains like an empty instance, instead of pointing to the item in my list
When successfully assigned to anything, having a reference type, the variable stores the reference to this "anything", and modifying the value is the same as modifying, in your case, the list's item
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
I think I'm following
It will be empty if the original list's item is empty too
Are you sure you got stuff in the list
If it's null, the reference won't be stored
I'm gonna triple check
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 🙂
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.
how can i detect collisions with a charater controller
I've been coding for 30+ years, and this is all so much new to me, and so much fun. But bad rookie mistakes are happening 😄
It's important to not overcomplicate things and it would have been much better if I was able to listen to my own advice.
Haha preach
My game was actually working before i started refactoring everything ...
Sometimes I get up for a smoke leaving my game in a working state. I come back and it does not work anymore.
Perhaps, you would prefer your browser over discord for questions, which have already been answered many times there?
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?
Joystick. So, you need to convert direction to rotation?
If you're only using one axis, you should exclude y and rotate your character on Vector3.up based on x
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)
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.
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
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
Step 2 is click those links..
3 also would be clicking the link to learn more
Do you not know how to debug code?
not really im like a absolute beginner
definitely click on the link provided
i clicked the debug bug do i just go through all the options there
Just logging will do for now, the rest can come later
found something that says debug on the top left of the screen
not the same thing
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?
Are you getting any errors
nope
Show the inspectors of the clones
the script?
The whole object preferably, but with this script visible
this is the script
I asked for the inspector
whats the inspector
The window that is labeled "Inspector"
The object
the inspector of the clones
This doesn't have the script on it
i know but the clones spawn through the script
Okay, so what's supposed to move them
enemy script
what enemy script
There are no scripts on that object so how do you expect it to move?
Okay, and does the enemy script somehow affect objects it is not on
yes it affects the movement and speed
How?
It could if he wrote it like a ecs system ☺️
What makes this script affect objects it is not on?
i think the enemy and waypoints are the main parts of the movement of my objects
You still haven't answered me
Can you show the enemy script ?
How does this Enemy script move this object?
I think you are missing the point, if a script is not on an object it does not run
Okay, so this script moves the object it is on
i get that but im stilly trying to get the script on my clones
And, as we have discussed, it is not on the object you're expecting to move
so, how are you expecting it to move
ok what am i supposed to do ?
Perhaps you should put the script that moves the object it is on, on the object you want to move
Add the Enemy component to your enemy prefab
i did
No, you didn't
Not according to your screenshots
You literally sent a screenshot proving you didn't
This object does not have the Enemy script
This object is a different one
Did you apply the change to the actual prefab you are spawning ?
This one has the enemy script on it
Nope
not according to your screenshot
Show the prefab
that green + on the component's icon means it is an unapplied override 😉
The blue margin and the green "+" icon shows that it was added later on, compared to the prefab
im still confused
You did not put the Enemy script on the objects you want to move
You have put the Enemy script on an object
but not the prefab
and therefore, not on the clones
yeah but where do i put it on
the prefab
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
The object in your scene is a i stance of the prefab
The actual prefab lives in your project folder where you saved it
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
You can apply the change from tue scene to the real prefab fron the override menu
it was in a different folder so i didnt really know how to do them at the same time
oh i finally found it i think. Seems to be SplineContainer
SplineContainer is the name of the component's type
❤️
dang i was just barely too slow lol
lol no worries! appreciated anyway to know for sure haha
You still don't have the EnemyMovement script on hte enemy per the video from the looks of it
ok
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?
correct, that gets evaluated at compile time
https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQMwAJboMLoN7LpGYZQAs6AsgBQCU+hxTAbgIYBO6AHugLzpx0YdDHQAqdAA4A3IyIBfZPKA===
fantastic, ty. it's just clearer to do it this way sometimes, when it's otherwise not obvious how you get the 'magic number'
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
That would imply that it's frame rate dependent.
Indeed
I'd also remind you that we can't read your thoughts and have a peek at your code without you sharing it.
Math.SmoothDamp is framerate dependent, right?
No. On it's own it's just a function.
Unfortunately can't provide the script at the moment, sorry
Then come back later when you can.
A code issue can't be solved without having the said code.
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
A common cause might be you using delta time where you don't need to, or not using it when you do need. But that's just an assumption. There could be many causes
SmoothDamp is just some math it is not even framerate related
I see, I'll look into it when I can. Hopefully we can work out a concrete solution tomorrow
Right. That makes sense. Thanks for clarifying
Sometimes stupid questions slip out of me
Anyways, I'll go now
Thank you for trying to help anyway
Not stupid. There's always gonna be things you don't know, and without asking or researching, you can't learn
Also true 🙏
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
is dashing gets put to false when grounded
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
huh so why did you put the code that way
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
well make it distinguished bool isAirborne or something. Send the full script, what is even going on with that coroutine
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
if (isGrounded && isAirborne)
{
DoSomething();
}
then set airborne to flase. Should work
or forget the bools and start making a simple fsm
this is the way
what is a fsm
finite state machine
for this fsm would i only have to include states when i am jumping, grounded, and landing?
That is up to you to decide
grounded can be bool
alr
thanks fsm's sound like very important for making games will implement it
for now , could just put a landed bool or something to set it once
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.
how do i learn how to code
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
check pins
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; }
}
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
nice, and can the opposite be done as well? some kind of "cast to Test"?
yep, exactly the same way
like this: (Test)integerVariable; ?
yep
enum aka = exciting number

Quick question, how do I use headers properly, my code looks like this
But in the debugger, its not showing the headers
ur in debug mode, yeah that wont work
How do i get out of debug mode?
3 dots menu in inspector
Ah , i got you, thanks
Does anyone know how to join games via P2P by using a generated code rather than IP address?
#archived-networking
This is certainly not a beginner question
lol not sure because its like beginner for multiplayer
Multiplayer and beginner don't really go together well lol
But there's a #archived-networking channel for that.
Wasnt sure if that was for multiplayer or like job connections lol
is anyone familiar with the unity splines? this one, https://docs.unity3d.com/Packages/com.unity.splines@2.6/api/index.html
ive looked through the api and i dont understand it because im new and im trying to automatically add a instantiate that looks like this.
Make it a configured prefab and instantiate the prefab🤷♂️
thats what i thought of doing but im not sure how, any guides?
Also I recommend going over the beginner pathways on !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks
wait, is it possible to grab just the instantiate component from the gameobject and put it on another gameobject.
No
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
You can check the documentation of Instantiate and what it returns.
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);```
Have you tried putting a breakpoint on that line? May be worth it to see a bit better detail on what is going on
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?
Your declaration would have the default initial value for the backing field set to an empty list of integers. It shouldn't be throwing an error. Likely you've modified the variable elsewhere.
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.
i have no clue why this isnt working
you have a function in your function
Keyword 'local function'
Show full !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Move it outside of the other function scope
You've practically placed it inside another method.
For instance:cs private void Update() { void OnCollisionEnter2D()//Local function { } }
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Both of those functions are inside another function
can you like underline the function its in cuz i literally put it under the class, its not under any function
Don't post an image. Instead, copy your code onto a paste site (save) and paste the url here.
I would, if you'd actually post the code
can anyone like have guide or tell me how do i integrate voice recog
how tf does this work
I've already sent the bot twice
Here it is a third time. !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
!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");
}
}
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
read the bot message
im sorry
It's a thing for you to read
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");
}
}
Wrong channel for non-coding questions. Try #💻┃unity-talk and make sure to provide more info - !ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
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");
}
}
//
stop
read the bot
and post the full script
If you cannot provide the entire script we'll not be able to point out your enclosed method.
You need to use the links (paste/save) and post the url here.
Do you
Dude the flking entire script..
That method has no errors. You've simply place it inside another method.
FUCKING HELL I'LL JUST LOOK IT UP
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
I DONT KNOW HOW THIS WORKS
I don't know what you're expecting at this point
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
As-is, this looks correct. Did you save the script?
Show an image of the console error from the Unity Editor
Full stacktrace pls
That's not the unity editor. That's your ide.
oh
The error was from PlayerGeneral.cs btw and not the one you posted unless the class name and script name explicitly do not match
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
Okay. So it's the correct script, but this is a different error. You have the wrong parameter type for the function
Still waiting for the console log window and stacktrace to validate error
wdym i used the autofill feature it cant be wrong
Look up OnCollisionEnter2D and see what parameters it takes, and compare them to yours
it doesent display anything cuz the thing doesent run
and no warning or error
i've seen it
The console window would always display the errors
Nevermind, you had a warning about local function not being used.
It won't display
This one would actually be a runtime error in unity
But VS extensions would detect the incorrect signature at compile time and give a warning
Or be completely ignored - undefined behavior
I still suggest doing this @mint imp
im so sorry about all of this
yall were right it was the parameters
please forgive me for lashing out at yall
Don't trust code suggestions btw. They CAN be wrong
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
Debug where it's invoked
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
When do you actually invoke the event? Likely before subscribing
it's actually in the Inventory script too, so it should've called Start by then not?
🤷♂️ I dont see the code for it
Either its subscribed after you invoked the event, or you removed it from the event before invoking.
what do you mean? it's this not? (Inventory script)
{
EventManager.AddSkillToItem += AddSkillToItem;
}```
That is subscribing to the event, not invoking the event
That adds AddSkillToItem to the list of things to be called when the event is invoked
I invoke it in another function in my inventory script
EventManager.StartAddSkillToItemEvent(skill, item);```
and that log is showing too
Just put another log in the Start and check so nobody needs to speculate
when is it being invoked, and yea do what Nitku said then show the logs
Also log the unsubscribe
Alright, so my Start function of the Inventory script is (no longer) being called, how does that happen?
the script is not enabled
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
Assuming this is System Action, you could probably check if they're actually subscribed using
https://learn.microsoft.com/en-us/dotnet/api/system.delegate.getinvocationlist?view=net-8.0 before invoking (for debugging purposes).
Uff, yeah I have the GO the script is attached to set to disabled by default lol
thx 🙂
and the important lesson here (again) is verify, don't assume
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?
The instance of the script exists, the fact that the Unity messages have or have not been called is purely a function of Unity
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?
yes
or is just calling Start ok too?
just make sure to unsubscribe as well
Not a good idea
I wouldn't do that, Start might end up being called twiice
It will then run twice
why? how?
Typically I try not to use awake/start when unnecessary if I need a specific order to complicated things.
When you enable it, it will run
If you called it already, that is two times
Oh, you were asking about unsubscibing. My bad
Why, because you should ALWAYS unsubscribe events.
How, OnDestroy is favourite
but my events need to stay subscribed as long as the game runs
I never destroy the script
But Unity does
Is this object in the DDOL scene? Itll be destroyed when loading a new scene if not
I never load new scenes
you should reeally find out about Unity and C# workflow
Will the game run forever or close at some point? Do you save and load I mean
Well incase you end up doing so, it's good practice to also unsubscribe.
Having reference of an object would allow you to call members (field, methods and whatnot) from it. The script being enabled/disabled would simply determine if certain Unity callback methods are fired by Unity.
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
nope, game loads on open and saves on close, never loads/closes scenes except for the main scene on game start
but it make sense to unsubscribe as best practice in case I ever do add more scenes
Ok, so yes is the answer. It loads and saves
Then the objects will be destroyed
Also If you build your game with IL2CPP and the game exits before you have cleaned up properly, i.e. unsubscribed events, it will be considered a memory leak by the OS
is unsubscribe just
EventManager.EquipEquippable -= EquipItem;
or do I need to look up how to do it?
I'll just add it to be sure then
good plan
I have an issue with the configuration of a gameobject, that's an inspector thing so what's the proper place to ask?
Sword is my Item
Health Orb is a Skill attached to that Item
Why does item.GetComponentsInChildren<Skill>() not work here?
thank you, it's probably something stupid with some checkbox I might not have seen so I should probably cover all my bases before that actually
Ew cuz it's inactive ofcourse 😭
r there any difference between Update and FixedUpdate?
yes
fixed update is for the physics system
it runs at a different rate than Update
thank u
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).
not sure what you want exactly.
i guess just learn about scriptable objects if you havent heard of them yet?
I'm quoting this from my brother: U need to plan how to implement a skill system
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...
It's a good idea to first design the domain of skills you want, just on paper, before jumping into the software design. The software design will be determined by the kinds of things you want to be able to express in the system.
He asks how will I get the skills into the game persay.
Like do I make a database out of each int function?
probably Scriptable Objects
Again it depends what you need and how you want your design workflow to work.. there are many ways to do it. Not sure what you mean by int function here, sounds way too specific at this stage of design
Some people use spreadsheets
Some use ScriptableObject
Ah
As in, do I need to make a database for every int function I add?
And do I dump it all into a VSCode script for good measure?
@deft grail Something like this for where all the Skill/Stat database would be stored in: https://hastebin.com/share/tubepodelu.java
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yeah i guess thats something you could do
Yea, that works.
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
It is highly unlikely that any modern monitor/graphics card will support a resolution below 640/480
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?
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)
Rounding? No float value except 0 will ever be ‚accurate‘ though
im just afraid that if i use a threshhold thats too big, i will end up clipping through very shallow ramps
What are you trying to do that this even matters?
non-rigidbody based character controller
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)
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
hmm so i should just add like a threshold of ~0.001f
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
im more worried about terrain ig
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
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
yea i havent gotten to that part yet
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
I was setting up the slashAnimPrefb wrong
help, i want to recive a unity project via version control
friend sent me project but all i got an empty project
This is the coding channel, maybe you ought to ask in the non coding channel #💻┃unity-talk
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
just make one then? you can name it anything, "idle" if you want
if you right click the empty area you can create an empty state
and if i put nothing in it the base sprite will remain? damn, should have just tested it lul xd, thx for the answer
yeah, because its not changing any of your sprites or anything.
even if you made an actual animation if you didnt change anything then it would just be the same
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); } } }
use physics to move
you are just teleporting the player
Physics ???
rigidbody, or CC i think should work too
ok
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); } }
what doesnt work? also dont use Time.deltaTime with physics
oh ye i forgot to delete
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); } }
what doesnt work
what happens
i cant move
think you need to combine into 1 vector and use only 1 add force, not sure exactly
ok
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)?
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);
}
}```
you should not be using Input.GetKeyDown in FixedUpdate
why ?
because it does not fire every frame and GetKeyDown is only valid for 1 frame
ohhh ok
well your using GetAxis so its not AS bad.
but try doing GetKeyDown and you will see the problem
so getKeyDown for every key ?
GetKeyDown(KeyCode.A) is how you use it
you can do any key
but ideally these days should be using the new input system
hi
mate your gonna get banned
what is the new input system
its not "new", but if you go to the package manager you can import input system
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
ok
never lil bro
!ban save 1209548762985402500 Racism
rando_rm was banned.
what
I seem to recall Sebastion Lague has one for his cave generation vid series
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);
}
}
}```
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.
oh wait i thought it does it for 100 frames lol
Nope
From start to end of Update is one frame
thx for the reminder! with that said, what should i do to say, move until it reaches a specific coordinate?
add an if check to see if it's there if so break?
but won't the if loop run in one frame as well?
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 :/
A loop makes code run multiple times
if will just run once per frame
thus acting different than the loop
which loops until it completes
dam i finally cleared the concept
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
@paper tangle Please don't crosspost.
I’ll check t then, thanks!
I'm curious as to whether putting the Update() class into the for loop would work
Update class? And, no it wouldn't, you would get an infinite loop
Ah okay. I'm just asking as someone who has no idea what he's talking about
then fyi it is the Update method not class
Ah right
good bit of lateral thinking though, shame it would never fly
Does anyone know of a good tutorial on scene loading in vr, and displaying a logo during the fade?
try asking in #💻┃unity-talk
If ur sliding something across multiple frames use a couroutine or async&await
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
Does the color you're setting it to happen to have 0 alpha?
You're likely making it transparent
I have no clue how to find that as it wasnt an issue in the tutorial i just copied what he did exactly
The alpha channel specifies to opacity of a (). Colors are represented in digital form as a collection of numbers, each representing the strength or intensity level of a given component of the color. Each of these components is called a channel. In a typical image file, the color channels describe how much red, green, and blue are used to make u...
the 4th color bar slider
It's just a general concept of color, it's not a Unity thing
I didn't even see that... nor would have known what it was until i was told
yeah that fixed it
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; } }
Step 1, add some debug logs in there so you know where your code is trying to go vs. not
oh ye ty 🙂
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
Last time it was in FixedUpdate. If that's still the case, they'll encounter massive issues with GetKeyDown desyncs
its in Update() but i dont know why my player move only if i spam the key
rb.AddForce(Vector3.back * speed); looks suspicious, you don't really want speed in an add force call
what do you do with horizontal and vertical input out side of this code
Because that's the purpose of GetKeyDown, which triggers once on key down, even if you hold down the key 10 seconds
ohh
so what is the correct key for this ???
its for my animation
GetKey(), which returns true for as long as you hold down the key
For reference, GetKeyUp also exists, which triggers once, when you release the key
does it exist something else for my bug (my player can noclip in wall)
Are you moving the player with its transform anywhere else? In this script, or in another
i was using transform.Translate but when i was running into wall my character sometime noclip when i asked on discord someone told me that i have to move with a rigidBody to fix this bug
is there a code to scroll to top of inspector via code?
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;
we have a method that moves a component to top of the inspector, would be nice if the scroll follows through
but what can i do ? my player can noclip in gameObject 
that's an entirely seperate issue from your input
{
verticalInput = Input.GetAxis("Vertical");
horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.forward * verticalInput * speed * Time.deltaTime);
transform.Translate(Vector3.right * horizontalInput * speed * Time.deltaTime);
}```
Is update called before the frame is rendered?
idk its FixedUpdate()
Update runs before the frame is rendered according to the excution order
damn, too slow . . .
Triple
so it seems like pre-render
ok sounds good
someone can help me my player noclip in wall 😭
Moving a rigidbody with transform will not respect physics
Should use rigidbody.AddForce/velocity instead
i have already tried this but the movement are weird
if (Input.GetKey(KeyCode.W))
{
rb.addforce(vector3.forward * speed);
}
else if (Input.GetKey(KeyCode.S))
{
rb.addForce(vector3.back * speed);
)
that will not even compile
what do you mean ?
no such thing as vector3
did you configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
it should tell you vector3 is wrong
its just an example
[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)
what is the issue
what is an issue ?
I see no reason for that code to even be in Update
idk
🤔