#💻┃code-beginner
1 messages · Page 128 of 1
yes, that
you are using build and run so the port number used is not fixed
yes
It doesnt
add another line for PlayerPrefs and try
ok, does your browser clear cache?
no
you still didn't answer what is 'Game Saved 0' ?
Game Saved 0 is how much "gold" is saved
Because it didnt load in this case so it just keeps saving fresh state
try loggging the length of the save string
I can log the whole save string?
also after save, read it back straight away
you can log anything, just make sure you are actually saving something
Is it weird that build can take few minutes, but if I restart windows explorer the build takes 1 second?
build.js(wasm) is where I am stuck at building most of the time, but if I cancel it then restart windows explorer and try to build again it will be instant.
On Save:
/idbfs/0634cbebe13ad9e3d93ee318fd86dd00/Gold.json
{"Gold":8.0}
Game Saved 8
{"Gold":8.0}
show code
Load:
FILE PATH ON LOAD: /idbfs/0634cbebe13ad9e3d93ee318fd86dd00/Gold.json
private void SaveGame()
{
GameSave save = new();
save.Gold = Gold;
string saveData = JsonUtility.ToJson(save);
string filePath = Path.Combine(Application.persistentDataPath, "Gold.json");
Debug.Log(filePath);
Debug.Log(saveData);
File.WriteAllText(filePath, saveData);
Debug.Log($"Game Saved {Gold}");
Debug.Log(saveData);
}
private void LoadGame()
{
string filePath = Path.Combine(Application.persistentDataPath, "Gold.json");
Debug.Log($"FILE PATH ON LOAD: {filePath}");
if (File.Exists(filePath))
{
string saveData = File.ReadAllText(filePath);
Gold = JsonUtility.FromJson<GameSave>(saveData).Gold;
Debug.Log($"Game Loaded {Gold}");
}
}
[Serializable]
public class GameSave
{
public float Gold;
}
Unity warning:
Saving has no effect. Your class 'UnityEditor.WebGL.HttpServerEditorWrapper' is missing the FilePathAttribute. Use this attribute to specify where to save your ScriptableSingleton.
Only call Save() and use this attribute if you want your state to survive between sessions of Unity.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
Debug.Log(filePath);
Debug.Log("saved:"+saveData);
File.WriteAllText(filePath, saveData);
Debug.Log($"Game Saved {Gold}");
string saveData1 = File.ReadAllText(filePath);
Debug.Log("read:"+saveData1);
Debugging 101
/idbfs/298968e364427a4a676ea38764ef47c3/Gold.json
saved:{"Gold":6.0}
Game Saved 6
read:{"Gold":6.0}
ok, so the file is saved
Maybe it really is the cors issue
even tho it has something to do with Unity cloud
which means your browser is clearing the cache
I dont know how
It doesnt delete anything when firefox is closed
But I never had issues with online games not saving
that is default behaviour for the browser unless you tell it different
then this is the worst solution for save/load system 😄
There is no way I can force players to change their hidden browser settings just for my game.
yes, that's why online games dont save to browser but to backend storage
So how come playerprefs work?
no idea, I dont use them
So what do I use in order to have a working save/load system in webGL that also works on other platforms?
you'll need a backend server
I dont believe that...there has to be a way to save it locally.
not in WebGL, you are not given access to the local file system
There is localstorage, indexedDB, playerprefs(those actually work without backend server)
afaik playerprefs use indexedDB too
but indexdb is what you are using now
well thats the issue.
if you are sure PlayerPrefs will work for you why not just save your json string to playerPrefs and have done with it?
We might do that, there were some reasons against it but if nothing else works we will do it.
I'm pretty sure it does save the file to IndexedDB. The contents are saved as an Int8Array to FILE_DATA.
Nothing I tried allowed me to load the data
It fails at:
string filePath = Path.Combine(Application.persistentDataPath, "Gold.json");
if (File.Exists(filePath)) // Fail
Do you restart the game with build & run in the editor?
persistentDataPath changes for every build
I build + run then I refresh the page after playing for a bit + saving the data
but the path stays the same
Don't build, just refresh
no
Even loading simple string doesnt work, it just fails at "File.Exists"
Fails = nothing happens since it fails to go through if statement.
guys how should i edit 2nd dictionary so that it works, first one is correct but obsolete and needs to be changed
You could try this: https://gamedev.stackexchange.com/a/184370
logically PlayerPrefs.Save should do the same thing as it's a generic function in JS
anybody?
Hello, im trying to make a simple fps controller for a school project. I have these 2 scripts to control the lateral movement, it seems like it should be fine but the capsule is not responding to my imputs at all. I get no errors in the debugger, just no reaction from the object. Any idea what is going wrong there?
whst is fixeedupdate?
btw the text is so small, next 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.
guys
Debug.Log("Set Resistances of all Levels");
string[] _resault = AssetDatabase.FindAssets("Level", new[] {"Assets/Scenes/Levels"});
GameObject _obj;
Level _lvl;
for (int i = 0; i < _resault.Length; i++) {
Debug.Log(AssetDatabase.GUIDToAssetPath(_resault[i]));
_obj = AssetDatabase.LoadAssetAtPath<GameObject>(_resault[i]);
if (_obj != null) {
Debug.Log($"We have an Object folks [{_obj.name}]");
_lvl = _obj.GetComponent<Level>();
if (_lvl != null) {
Debug.Log("We have a Level folks");
}
}
}
}```
doesnt print the "We have an object" and the "we have a level" logs. so _obj is null basicly and am not sure why
I have been staring at it for like half an hour and didnt see it. Thanks! works perfectly now
note the 0 references above it, a dead giveaway
ill try to keep an eye on it next time. thanks for the tip
is your FindAssets returning anything?
string path = AssetDatabase.GUIDToAssetPath(_resault[i])
_obj = AssetDatabase.LoadAssetAtPath<GameObject>(path);
_resault[i] is a Guid not a path
so now it works fine, it gets to "We have an Object" debug log, but _lvl is null, it doesnt seem to find the component
Debug.Log("Set Resistances of all Levels");
string[] _resault = AssetDatabase.FindAssets("Level", new[] {"Assets/Scenes/Levels"});
string _path;
GameObject _obj;
Level _lvl;
for (int i = 0; i < _resault.Length; i++) {
_path = AssetDatabase.GUIDToAssetPath(_resault[i]);
Debug.Log(_path);
_obj = AssetDatabase.LoadAssetAtPath<GameObject>(_path);
if (_obj != null) {
Debug.Log($"We have an Object folks [{_obj.name}]");
_lvl = _obj.GetComponent<Level>();
if (_lvl != null) {
Debug.Log("We have a Level folks");
}
}
}
}```
AssetDatabase.FindAssets("t:Level", new[] {"Assets/Scenes/Levels"});
Level is a component in the prefab
like this it doesnt return anything
then you may want to use GetComponentInChildren
ok
without the t:
yeah
same thing
as before
doesnt get to Level component
the Level component is in the gameobject itself, not in a child
show the inspector of one of the prefabs
that's not what I asked for
the Inspector of the prefab. like LevelTitan
I will try that, based on what I read so far this was supposed to be done internally in new Unity version, but maybe not 😐
I cant see why that is not working, I would suggest getting all components from _obj and looping through them to see what comes back
ok
like this it works
how do i get XR inputs with pure code? (new unity input system)
you have two options (examples):
Quaternion rightHandOrientationValue = default;
// Option A: action map created via code
InputActionMap xrmap = new InputActionMap ("My XR Input Map");
InputAction rightHandOrientation = xrmap.AddAction ( "Right Hand Orientation" );
rightHandOrientation.AddBinding ( "<XRController>{RightHand}/orientation" );
xrmap.Enable ();
rightHandOrientationValue = rightHandOrientation.ReadValue<Quaternion> ();
// Option B: Hard coded via Static API
rightHandOrientationValue = XRController.rightHand.deviceRotation.ReadValue ();
you gotta figure these out yourself, there is no list
ah.....
!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 all, I have a question regarding how I'm handling something in my game. I have a hand of cards and currently when I include this code in the Card's script, it behaves like the 1st video:
https://gdl.space/silesinina.cpp
But when I add this code to have it appear in front of the other cards, it behaves like the 2nd video:
https://gdl.space/jayawebane.cpp
In the 2nd video, the cards aren't rising at all, but when the pointer leaves the card, it still drops down. And there's also just weird behaviour going on.
what does AddAction() do?
like what's the difference between AddAction and AddBinding
Does anyone know what I could be doing wrong with my code? I've also tried using stuff like transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y + 20, transform.localPosition.z); instead of cardTransform.anchoredPosition = new Vector2(cardTransform.anchoredPosition.x, cardTransform.anchoredPosition.y + 20); but none of it works
AddAction creates an action, i.e. an abstract input event you want to query, AddBinding defines how that action is triggered specifically (button presses, joystick movement etc.)
they key to understanding InputSystem is to understand that it is designed to make input fully abstract and do away with the idea of a button press
so yes, you need a binding
you need to define what a given action is
if you use the static API (example B above) the common inputs you'd expect from a simpler input system (like the old one) are premade for you
does the name of the action matter?
no
you can however search for actions by name (but you should avoid that, just for sanity's sake)
is there any way to know if a binding does something? or what that binding outputs?
I wanted to make a timer with this code
private void Update()
{
if(timerRunning)
{
timerMs += (int)(Time.deltaTime * 1000);
UpdateTimerUI(timerMs);
}
}```
but if I start the timer on a different pc then put a recording of my and the other pc ontop of each other so that they start at the exact same time, after 19 sec I have a difference of about 1 sec is this normal? And if so how should I do it then?
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using System;
public class PlayerHealth : MonoBehaviour, IDamagable
{
[SerializeField] private PlayerStats stats;
public static event Action OnPlayerDeath;
private void Start()
{
stats.CurrentHealth = stats.MaxHealth;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.P))
TakeDamage(1);
}
public void TakeDamage(float damageAmount)
{
if (stats.CurrentHealth >= damageAmount)
stats.CurrentHealth -= damageAmount;
else
Death();
}
private void Death()
{
OnPlayerDeath();
}
}
ive got a question to this code snippet:
as you can see i have this static Action which every script can subscribe their methods to.
is this considered bad code? and if so can you tell me an alternative to create a loosely coupled connection between different class (except for the observer pattern
Yes, it's expected – you're truncating the milliseconds each frame so the error compounds quickly
it should be
timerMs += Time.deltaTime * 1000;
UpdateTimerUI((int)timerMs);
you need to know the type, but you can figure it out if you make a input action assset in the editor, it basically has all the possible values/types
the "real" way to use InputSystem is through such an input action asset anyway
you use the code-api only if you want to make a convenient default config for prototyping or quickstart or if you wrap the whole thing into your own tooling for special needs of a complex project
actually, different question, I've got two types of items that can be displayed in an inventory slot, so I basically copied over the display inventory script and adapted it to fit this structure item slot, but this doesn't feel at all right. Is there a way to just have one class that can accept any type so they aren't both duplicated?
chance is written with an c not an s
lol
If I just made an interface for these different types of Ui slots, would that work do you think?
what would joystick click be called?
in binding
Is there any simple and very quick way to add some sort of graphic on a gameobject so I can indicate direction?
Im working on a simulator for school and need to know which way my cylinder is facing
While its running
Dont wanna spend a bunch of time on unnecessary stuff, its just for me
Slap a cone on it as a child object?
Draw some gizmos?
lots of ways
What would be the easiest way to slap a triangle graphic on the top of the cylinder?
just a random triangle of some different color so that i can see which way its facing
without adding more objects, just the graphic
I shared the easiest way I can think of
The axes on gameobjects, do they turn with the object? So for instance the blue arrow (forward) does that rotate with the rotation of the object?
In Scene view
Or is it locked as some sort of global axis
you can toggle it with the X key
Ah cool ty!
Got the Ui slot script attached to the slotPrefab, and I want to change the value before instantiating it, but it's not letting me access it. What might I be doing wrong here?
Hey, can someone help me, i have a Raycast that should, when it hits an objects with a collider set as a trigger Destroy the object, yet the Ray just goes through the Trigger, any ideas? https://hastebin.com/share/vekekupubu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
mouse over the underlined red text and read the error message
is the first Debug.Log printing? If so what does it say?
just says slotPrefab could not be found, but I've got the variable up top with it assigned in the inspector too
yes, it hits the object behind the Trigger
show the code
show the inspector for the object with the trigger collider?
what I've got so far
Also note "Queries Hit Triggers" in the physics settings.
https://docs.unity3d.com/Manual/class-PhysicsManager.html
ive got it activated, i think
you're missing a semicolon on that line and also... it's just not a valid line of code at all
since it's not doing anything
That's a 2D collider
You're using a 3D raycast
You would want to use Physics2D.GetRayIntersection
I know there's no semicolon, but the issue is that it isn't filling out the CorrespondingInventoryItem, and I'm not sure why
btw since this is UI stuff why are you using SpriteRenderer and colliders in the first place?
thanks!
because you forgot the () in your GetComponent call
you need () to call a function in C#
where does it say I'm using those? don't know what spriterenderer even is
Right here in your screenshot
You have SpriteRenderer, Rigidbody2D, Collider2D on this object
wrong reply
How can I shift the transform.forward vector a certain amount of x to the right or left?
Say I want a raycast a little to the left of the forward direction
Can't believe I didn't spot the brackets though
yeah sorry my bad
you mean you want to rotate it by a certain number of degrees around some rotation axis?
i've not used too many methods that need the <> so I guess I assumed that replaced the brackets
Well I mean i am shooting a raycast like this
Ray rayForw = new Ray(RVOAgents[i].transform.localPosition, RVOAgents[i].transform.forward);
But I also want to shoot one abit to the left and a bit to the right
right and I'm asking you to clarify what you mean
when we're talking about a direction vector generally you mean you want to rotate that vector
Not looking to rotate anything, i just want to shoot a raycast to the left and right of the forward vector
shifting it to the right or left might mean moving the position, not changing the direction
I want the forward to stay as it is. Just want to based on the forward, shoot to the left and right of it
Do you want to change grewen to red?
Or change blue to magenta?
blue to magenta is a rotation of the direction
green to red is moving the origin of the ray
Yes blue to magenta
so yes you want a rotation
but i dont want the gameobjects actual forward vector to rotate
But yes i do want an "imaginary" one to rotate that i can use
Lool, i was 100% sure he meant green to red
you can rotate the copy of forward vector
Yeah i figured that was the case with praetors reply
makes sense
Ill try it
Yeah worked, ty peeps
With raycast hits, I need to check after each raycast right, I cant cast 3 raycasts and then do stuff based on the hits?
Since it doesnt differentiate the hits ? probably just writes over them?
use 3 different variable to store the raycasthit result
Yeah was just about to write that, but i have to store between each cast that is
Yeah i understand now ty
Hello! How to make it visible?
That square which is an image
(Im using a Scroll Rect component)
Physics.Raycast lets you ignore certain layers, is there a way to do the opposite, make it only HIT certain layers?
Or rather, just one layer i need it to hit
I mean, you can do whatever you want as long as you understand how to store information and process it in C#
invert the layermask
actually the normal behavior is to only HIT the layers in the mask
A little vague wording i guess but sounds to me like its specifying which i want it to ignore
I mean I guess I can just let it hit everything and then check whether the object hit is in a certain layer
Tho it will mean that the ray is cut short in the event of ignored layers but whatever maybe its fine
Ah nvm i understand it now, my bad. Been a while since using Unity, a layermask is a layermask, not just one layer lol
Is there a difference?
Is there a difference between using a parent game object for movement logic and a childed capsule for collision and just simply using a capsule for it all?
I've seen some tutorials do systems differently and I just wanted to know if I should bother look into it
Are you asking if it matters if the collider is on the same object as the Rigidbody or a child? It doesn't really matter no
Oh alright. Can I ask why some people do these systems differently though? Isn't it just easier to use a single game object for the collision and the movement logic? I thought it might help with interpolation or something
Wdym by "single capsule"? It's a single capsule either way.
I meant that a single game object has both collisions and rigidbody movement
There are many advantages to having the collider on a child object.
- It can be animated separately from the parent
- It can have custom scripts on it that for example have collision callbacks that apply ONLY to that collider (and not other colliders on the body)
- It can have a different layer and/or tag than its parent
- It can be scaled/rotated/positioned relative to the parent
Understood
But I'm having trouble with using the collider as a child
Because I created this simple script for teleportation
For some reason it messes up with crouching and collisions
you'd have to share details of the script and the trouble you're having
using UnityEngine;
public class Teleporter : MonoBehaviour
{
public Transform destination;
public GameObject objectToTeleport;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject == objectToTeleport)
{
TeleportObject(objectToTeleport);
}
}
private void TeleportObject(GameObject objectToTeleport)
{
if (destination != null)
{
objectToTeleport.transform.position = destination.position;
}
}
}
But since the parent game object doesn't have a collider, I decided to teleport the child
But it messes up the position of the parent I'm guessing
if you want the parent you can just do other.tranform.parent.gameObject
Or perhaps the safest thing assuming these are all root objects in the scene is other.transform.root.gameObject
Though I'd probably just use Transform directly instead of needlessly involving the GameObject, since you're only just accessing the Transform again
Makes sense
lmao
I wanted to have it so that clicking one spawns an item in the scene, which is what I was resolving earlier, but removing it from the UI isn't working as expected.
Currently got another issue when trying to remove a UI element from the screen. In this case I have a dictionary that uses an inventorySlot to point to a GameObject, the slot in the Ui that displays that item, which is assigned here as expected.
In the code screenshot, I can see that when the next scene loads it is correctly assigned as a pair in the dictionary
But then when I click on '2' and watch the execution, the value suddenly becomes null, and get this error
But I'm not sure why it just becomes null when the dictionary had the gameobject stored properly when the scene first loads
That last image tells you exactly why
"The object of type GameObject has been destroyed"
Which is exactly what happens to all GameObjects in a scene when the scene is unloaded
You still have a stale reference to a GameObject in the previous scene
Unity overrides the ToString() on destroyed objects to say "null", it's not actually null
in this case the scene isn't unloaded, from what I see here in the first screenshot it adds it to the dictionary when the scene loads
so i would have thought the gameobject it references is the one currently existing
You are somewhere destroying the object, either by unloading the scene or manually calling Destroy on it
I'm not calling destroy anywhere else bar the method shown a few messages above, but can't destroy it cause there isn't a gameobject in the value.
I've got no clue why else the objects would be unloading though
which method has Destroy? You should add Debug.Log statements to check if and when that's running
or use the debugger
you can also drill down into the thing here instead of trusting that "null" string there to see if it's actually null or a Destroyed object
just this one
it's bugging me btw that you write this whole thing itemsDisplayed[Inventory.InvContainer[i]] instead of just obj which is the same object in that earlier screenshot lol
yeah this looks like it's probably the culprit
but it's not actually destroying anything since there's nothing to destroy
since the dictionary value inside is always null for me
maybe you're looking at a completely different dictionary
a different inventory reference, different co[py of the script, etc.
hard to tell from these limited screenshots
hang on, think I may have an idea
hi can someone help me please?
upload as mp4 to get embedded in discord
so in this case, my inventorySlot consists of a custom Item object alongside a count. At the start I add an item to the dictionary with that slot as the key and the object as the gameobject. i reduce the count by 1 in a script outside of this one, then I want displayInventory to change to reflect that. But if I reduce the count by 1, then use that as a key, will the fact that the count isn't the same mean that It can't find the gameobject and returns null?
I'm having a hard time following your explanation
your setup seems a little overcomplex
can someone explain me why my animation does this? i'm using first person starter pack by unity, loop time is turned off
probably is, I really don't know the best methods to do this sort of stuff since I'm brand new to all this
looks like it's doing exactly what you told it to do? What's the issue exactly, the fact that it's looping?
Hey this code makes no sense but I'm curious. How do you access different components of same type on an object?
I assumed GetComponent would return an array but it does not apparently.
GetComponents returns an array
the singular version only returns the first one
you can also do:
[SerializeField]
Collider myCollider;``` and drag a specific collider into the slot in the inspector
Often if you have multiple colliders, putting them on child GameObjects can be best practice though
yes looptime is off, and its too fast even if i set the speed at 0.1 . why does it spin like this?
well for one you have defined the animation as taking only 0:04 which is 4 60ths of a second.
or about 66 milliseconds total, which is very fast
As for looping, can you show the inspector for the animation clip
lol
yea wait a sec
it is actually not doing what im telling him to, look at this it looks like a washing machine 
perhaps your code is explicitly running this animation
sorry wrong vid
i dont have a code mentioning it
cool washing machine
its slow at the start and its faster every time it repeats itself
why this code for make footsound is wrong?
Use https://docs.unity3d.com/ScriptReference/AudioSource.Play.html and https://docs.unity3d.com/ScriptReference/AudioSource.Stop.html to start and stop an audio source.
Also if you play every frame it's not going to work properly, it will restart every time you call play
do you mean .Play()?
so you'll want to do it only when you start and stop moving, not every frame
had a look through all my other classes and set up some debug log messages, but I still can't find why it's setting it to null. Is it possible that the key has changed so it can't find the object rather than the object not existing?
i would make a custom property for this
use a custom setter, that gives a Debug.Log every time it is called
You would get a KeyNotFoundException if the key doesn't exist in the Dictionary
IndexOutOfRange/KeyNotFound mean the array/list/dict are not null, but the entry is not in there
NullReferenceException => list/array/dict is null
what if the dictionary key is the slot but a custom int count inside is different to what I pass in? Here for instance the actual count for the item slot will be 1, but the itemsDisplayed dictionary will still have 2 since it's been reduced by 1
I don't really know what "count" is referring to here
the number of items in an inventory slot
i think you want TryGetValue
what does the number of items in the slot have to do with this though
what is itemsDisplayed exactly? A map of what to what?
Some internal inventory object to a UI GameObject?
Was wondering if the fact that the count that is stored in the key I'm passing in is different to what is stored in the dictionary that maybe it isn't finding the right value
It's hard to say because I have no idea what the key is
is the key a struct?
If it's just a reference to a reference-typed object, the data inside doesn't matter
in fact the data will always be the same everywhere you look at it because you're referencing the same object
if it's a struct, then yes you have issues here
it's supposed to map an InventorySlot to a gameobject, so an inventory here would be made up of inventory slots, so I thought I could use the dictionary to easily delete the gameobject by passing in the inventory slot it relates to
But I think it's pretty clear form your earlier screenshot that there exists an actual mapping int he Dictionary to something that is showing as null
it's a class, so it's a reference type
the only thing that matters is the actual reference.
so the count being different doesn't matter, gotcha
it can't be different
as long as you're referring to the same object
i see
it will have the same count, because they're the same object
that's how reference types work
your variable stores basically a pointer to the object, not the object itself.
i assume the dictionary maps Item key to int value?
i’m very confused by your code tbh
cause essentially all I wanted to do here was have it so that I can use the inventory slot as the key and change the details of the game object that way
so Item is.. .a GameObject?
Still kinda looking to the answer to this question
we’d need to know the types at play here to do anything
and for adding to the count in the slot it works, as the previous scene. These ui elements would be the gameobject in the dictionary, and the inventoryItemSlot is the actual item in the inventory
what type is the dictionary 😵💫
did I not post it above?
no
it's here
public Dictionary<InventoryItemSlot, GameObject> itemsDisplayed = new Dictionary<InventoryItemSlot, GameObject>();``` in case the image isn't loading
So when this second scene loads, it should look at all the items in the inventory and create UI elements for them, adding them to the dictionary. Then when the Ui element is clicked it will remove it from the inventory, and then perform this method to change the UI number or destroy it outright depending on how it changes in the inventory. but here is where the gameobject ends up as null
layer mask should mask a layer when a doing a raycast, right?
the layer mask is the set of layers that are included in the raycast
only the layers in the mask will be included
it is some sort of filter
oh- thats
a bit confusing, right, thats why its not working
LayerMask is a bit mask. 32 ones and zeros, where 0 at position X means to ignore layer X.
Layer is the index (X) in that layer mask.
again you can drill down on those 0 and 1 elements where it's null to see what's up - but I think it's pretty clear those objects were destroyed somehow
so 0011 means include 1/2 and exclude 3/4
what do you mean by drill down?
oh I see what you mean
it's been taking longer and longer to load up which is strange
right then, so upon loading up the scene it's picked it all up properly. oh, and it's all just gone when I run the update
the gameobjects still exist in the scene which is the most confusing part for me
What scripts are on those objects? I suspect they're being destroyed somewhre else
BTW this definitely means it's a destroyed object
and not real null
got this one that handles clicking the UI, this one for actually removing the item, then it fires the event that runs the display update one
wait so- what if I write something like 2 or 3?
and is layer zero included?
2=0b10
3=0b11
i think it’s offset to be 0-31 actually
so 0011 would be 0/1 on and 2/3 off
i think
isn't layer 0 = none ?
what does that b mean?
0b means representing a number in binary
0b01 means the number corresponding to 0000000000000…0001 in binary
binary format, fyi 0x = hexadecimal
you shouldn't even really worry about htis. To define a layermaskj do this:
public LayerMask myMask;``` and you can set it up in the inspector
oh right thanks
you can also add/subtract layer masks, fyi
0010 + 0100 = 0110
there are good extensions to just automatically make consts for individual layers and layer masks
| bitwise or operator
I've looked just about everywhere and there definitely is not a moment where I delete the gameObject that inventory slot should relate to
what scripts are on the object?
on the UI element, just this which only does this
What does RemoveItem do
and InvContainer.Remove does?
cannot remove an element in a foreach
inv container is just a list so it'll remove it from that
how can i check if my player has bought an item and if so, make it non-interactable next time they visit the shop?
https://hastebin.com/share/pujuxowoge.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
not in a foreach it wont, also if you want to remove itterate in reverse
you';d want to save the data about which items the player has bought in some kind of persistent state
so like some kind of bool? and everytime the go the shop the game checks that bool?
that's underselling it
Probably not a bool
maybe more like a list of item names or ids
Looks like it did on my end, there were 2 cardboard items before the remove method is called
like itemsOwned: ["dagger", "cat", "lamp"] in some list somewhere proably belonging to a broader "game state" object
oh okay
and i would append the bought item to the list you mentioned whenever the player buys it correct?
yep
alright thanks!
I just think it's odd how adding items to it works in every other scene, it's just removing that isn't working
tbh I don't understand why this is happening in Update anyway? Why not immediately remove the things when you remove the item
THough I'm a bit unclear if this is running in Update or not
Actually now that I'm thinking about it, isn't it clear this code is the very thing destroying the object? Then you're looking next frame and you see a destroyed object there, naturally
You never actually remove it from the dictionary, right?
don't you also want itemsDisplayed.Remove(inventory.InvContainer[i]);?
nothing runs from the Update method specifically, I just use an event when the item is removed from the inventory
wait also if that thing is null, aren't you just destroying nothing? Why would there be a null key in the dictioanry in the first place? That's really odd
this is just... weird overall the more I think about it
If it's a list then actually yeah the index won't be pointing to the right place, that's fair enough. But even if I tries to destroy the object below it, the itemsdisplayed thing is already all null
If I run it through from the start I can see that before removing there are two cardboard items, which are then removed in the script that handles someone clicking the UI slot. Then since the inventory has been changed, it goes to update the display. and i can see that the container has the current slots and totals. The dictionary is pointing to the right key but then of course it's just null. And it's never ran the destroy method, these lines are the only two it runs through
I suppose the only other way I could try it is if destroy the object this script belongs to after removing the item from the inventory?
Is that possible?
might put a pin in this one. Spent 5 hours already trying to resolve it but i just can't seem to amend it
I can see now why people say to start off with smaller projects, if I tried doing a large one now I'd be so burdened by my awful script structure that I'd never be able to make anything work on a large scale
yeah
the system works great thank you btw! 🙏 however i think i messed something up as it only works while the game is running. whenever i quit and come back the items reset back to not being bought, why is that?
https://hastebin.com/share/onulacatuy.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
sorry for the ping btw
well sure I mean, you would have to share your ItemManager code but I presume you aren't storing this data anywhere except in memory
you would need some kind of saved game system to persist between play sessions
hmm okay
here is the item manager script
https://hastebin.com/share/evipilarab.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
and the saving system
https://hastebin.com/share/fomajitale.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Im coding a bullet but it doesnt seem to move when I shoot it
The way its setup is that when its instantiated It gets shot and then moves along the local position forward until it hits something, but it isnt moving forward and just stuck in the air, another thing is that it doesnt instantiate every time I press my mouse button
This is the setup
I'm very rusty so idk what im doing wrong
You have to put the transform.position part in the update or lateupdate method.
it only triggers once now
This method is in fixedupdate, does that not work?
Did you put a method in fixed update?
by making this static does that just mean you can get the manager without needing to look at the gameobject that has attached?
fixedupdate doesn't take count of frame drops
Down/Up methods only return true for one frame
If you put the script of the method in fixed update, then it won't work. It's not bad. Everyone learns from his mistakes. Fixedupdate is a method on it's own, so you're putting a method in a method now.
you could better do smt like:
... fixedUpdate() {
if (input...) {
script
}
}```
also this
you're only saving click count and clickadder
ah ok
The transform should be appart of the spawning method or if check
thats why it didnt shoot all the time
wait how come it's moving to the else part when they are both the same
and this will hide the layer I set up, right?
by making it static, the version of my itemID'S list remains the same in all scripts and instances of it.
oh so if there is another gameManager object on another scene it won't have all it's values reset?
oh okay, whats the difference between saving the id in GameManager instead of BuyItem?
Normally, members (fields, methods, properties, etc.) of a type exist on each instance of the type.
So each object will have its own data.
A static member doesn't live on an instance
There is always exactly one copy of it, and you access it with the type name, rather than accessing it from a specific instance
in this case, every time a GameManager's Awake method runs, gameManager is set to this
so, when a GameManager wakes up, it writes itself into that static gameManager field
If no GameManager has woken up yet, GameManager.gameManager will be null. Otherwise, you'll get the most recent GameManager to have woken up.
gotcha
This is a pretty common pattern for "manager" types. It's usually called the singleton pattern.
I've used static variables a fair bit in the past but the way unity deals with stuff just has me confused at times
I mean you want a centralized place to know all the items you have right? Isn't BuyItem just a single item?
but I could use that approach for my inventories perhaps
The main thing to keep in mind is what happens if a Unity object is destroyed
If the object stored in gameManager is destroyed (e.g. by a scene unload), the variable will return true if you check if it equals null
(because all unity objects do that)
if (GameManager.gameManager == null) {
Debug.Log("No game manager has woken up OR the latest game manager has been destroyed");
}
static fields live for as long as the program does, so the value will only change if you write a new one
What version of Unity should I install?
By default, pick the latest LTS (Long-Term Support) release.
Should be 2022.3.x
2022.3.16f1 right now, I think?
If you're following a tutorial that calls for a specific Unity version, pick that instead. You can generally just match the first two numbers.
well buyitem is on every single one of my items however it isn't centralized like GameManager correct? so would that cause it to lose it's values once i restart the game?
year.minor.patch
Nop, just starting by myself
when you retart your game your entire program stops running
nothing in memory will survive.
only files
although i believe 2021 is the only one that has example projects you can try out
or PlayerPrefs which uses the registry
Right. They're not available for 2022
I could try out 2021 first then
could do I suppose. I've had a lot of fun working through them
This one?
These projects, specifically.
Is it necessary for me to download any module?
I remember the FPS one
It was kinda futuristic
I didn't expect them all to have full on tutorials in them
oh okay i think i understand now. BuyItem is no good since although it exists in multiple places, it is just a single thing. with GameManager, it acts as a centralized hub for storing data. what i said about restarting the game doesnt matter as everything in memory goes away once i stop the game. the only thing that remains are files or playerprefs correct?
okay, thank you praetor! 🙏
You need a way to turn the game's state (which items you've bought) into data you can store
and then a way to turn that data back into game state
finally got it working my word. brute forced it in an ugly way but it functions at least. Thanks for helping out, Praetor, this is a lot harder than I thought
Trying to make a shooting system using a particle system. I want to receive different debug messages depending on what's hit using layers. Can anyone help me on why my Collision If Statement isn't working?
Nevermind, figured it out!!
should just need to be other.layer shouldn't it?
Yup! Thanks anyway!
talking about statics and whatnot, at the moment I have my inventories saved as scriptable objects, first of all - is that a common thing to do? And secondly, using that static method would it be easier to change how this here works so instead there is a static inventory object between scenes?
Making a 2D game where the player will have a shotgun, and I want the shotgun to push the player back with the recoil. This is my code at the moment but it's not moving the player at all when right clicking. Can anyone help me figure out why please?
How do I trigger an animation parameter bool with script
Maybe do += on the third if
you're setting the velocity in all three cases
Although, hm, you are keeping the X component in the first two cases
Yeah += is adding iirc
Yeah, sorry. Meant left clicking
The first 2 if's affect Y axis, the third affects X
so not sure why it wouldn't work
Check that your code is actually running with a Debug.Log statement.
Then make sure nothing else is setting the velocity of the rigidbody
oh, one other thing
Check the inspector to make sure GunKickBack isn't zero
If you didn't have = 500f when you first wrote the script, and only added that later, the inspector would keep the zero
Debug.Log works, and I also tried putting GunKickBack on the Y part, and it shot me upwards like it should
But for some reason, on X, it doesn't do anything
and I've checked inspector and script, both have 500f
Did you try what I told you
Yeah, also didn't work
damn
Could it be this that's affecting it?
But surely that's just to control the speed?
Actually it works now that's I've disabled that part, so it must be that somehow interfering
ofc the velocity of rb get overwritten
UR setting the velocity in Update and FixedUpdate
U should on be setting it in FixedUpdate
use addforce
make bool for the .velocity part
Two options.
One: Don't set the velocity directly. Just apply forces to move the player.
Two: Store recoil velocity separately. Add it on top of the movement velocity.
The latter will be easier to control, at the expense of physical accuracy.
@swift crag hey did you miss this message from me?
oh right, I forgot to reply
How could I add it on top of the movement velocity?
store a separate Vector2 for recoil velocity
then add it to the Vector2 you're creating in FixedUpdate
(and have it rapidly decrease to zero, too)
oh ok but doing multiple parameters is impossible? what would you recommend for functions that need multiple parameters?
there are variants for 2, 3, and 4 parameter functions
oh they're on the left i see them now. does that mean i need to do make a custom script for each? I can't just jump into my script and add this?
public UnityEvent<string, int> myEvent;
i must always make a custom script first where i override the class type?
How do i fix my yaw constantly resetting back to 0? ``` yaw = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * mouseSensitivity;
if (!invertCamera)
{
pitch -= mouseSensitivity * Input.GetAxis("Mouse Y");
}
else
{
// Inverted Y
pitch += mouseSensitivity * Input.GetAxis("Mouse Y");
}
// Clamp pitch between lookAngle
pitch = Mathf.Clamp(pitch, -maxLookAngle, maxLookAngle);
playerCamera.transform.localEulerAngles = new Vector3(pitch, yaw, 0);
Debug.Log("Controller Yaw: " + yaw);```
What you wrote looks fine to me.
but this part in the documentation confuses me "If you wish to use a generic UnityEvent type you must override the class type."
Oh! right, I forgot
Unity can't serialize a generic type properly (except in specific cases, like List)
So yeah, you just do a one liner class
public class StringIntEvent : UnityEvent<string, int> { }
That's all
It does not need its own script file.
Comment out the line yaw = ...
reading and writing eulerAngles can cause problems, since they might change (internally, the rotation is always a Quaternion).
Now i can only look up and down.
I wouldn't expect it to be resetting to 0 all the time, though
Any idea why I can't call Camera.main anymore, it says there is no instance
When is it resetting to zero? Sounds like you could look up and down at the start..
ok, thanks! never knew about this whole multi parameter thing being possible before so its gonna be super useful
That line was an issue. Replace that line with something better.
The object with your camera needs the MainCamera tag
Camera.main only works if there is camera with MainCamera tag
Its resetting to zero when i move my yaw.
Check the tag on ur Camera
You could also Just do [SerializeField] Camera _cam;
Its better than doing Camera.Main anyway
Hey, does anybody know what could cause that the walls are "shaking", it is also visible on ground, but not as much.
Ah makes sense
oh caching it nvm I saw ur message
this might be the same issue being talked about in #archived-code-general right now
When i disable camera movement all together and manually rotate my camera , it doesnt reset.
a few things to look at:
- don't use deltaTime with mouse input
- are you moving and rotating the camera in different places? FixedUpdate vs. Update, for example
I have been fiddling around and now this stopped working, it does not hit any raycast and I have a plane on the ground:
Vector2 mousePos = InputActions.mousePosition.ReadValue<Vector2>();
if (Physics.Raycast(Camera.main.ScreenPointToRay(mousePos), out RaycastHit _hit, 1000f)) {
mousePos gets updated every frame
I have an ortho camera
I found the issue, in the yaw =, i was adding the players rotation with the mouse, instead of the cameras rotation.
📃 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.
Ah, that'll do it
Sometimes I wish you could make using transform an error for a component
@queen adder3D It's just this: ```cs
if (Physics.Raycast(Camera.main.ScreenPointToRay(mousePos), out RaycastHit _hit, 1000f)) {
Debug.Log("hit " + _hit.point);
} else {
Debug.Log("Raycast missed"); // Called every frame
}
And this stuff fixed all of my jitter completely. Thanks for the help. The main issue was rotating the player instead of only the camera.
Thanks for reply. I don´t use deltaTime with mouse input and I also just update the camera rotation in the Update() method, which is in player script, when I tried using FixedUpdate() it got even worse.
Does the plane have a collider on it?
How do you move the player?
If u can see the plane and click on it should work
Make sure the collide is turned on
Are u using a rigidbody or CharacterController to move ur player?
It has something to do with cinemachine
Did you set the object with the Camera on it to have the MainCamera tag?
You shouldn't do that to a Cinemachine virtual camera
Those aren't real cameras. They just control where the real camera goes.
Camera and brain on same object with the tag
Also sorry the Rigidbody or characterController question was for 84muu3l
Question: Why is the player moving on its own, while the camera is moving, it moves right a few steps. ``` float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
// Calculate the movement direction relative to the camera's rotation
Vector3 forward = playerCamera.transform.forward;
Vector3 right = playerCamera.transform.right;
forward.y = 0f; // Ensure no vertical movement
right.y = 0f; // Ensure no vertical movement
forward.Normalize();
right.Normalize();
Vector3 desiredMoveDirection = forward * verticalInput + right * horizontalInput;
// Apply the movement to the rigidbody
rb.velocity = desiredMoveDirection * playerSpeed;```
Then I have another object with cinemachine camera. They changed the components in the latest update
Couple things RGT theres no reason to set the y axis on the forward and right variables
Vector3.forward literally returns a Vector3 (0,0, current_z_axis)
that's not Vector3.forward
Hi! I'm trying to animate my button but... After 2 hours I still don't know what am I doing wrong. Could sb help me?
they're cam.transform.forward and right
well, you haven't assigned anything to the animation field
You probably wanted a field that holds an Animator, though. Animation is a really old component.
transform.forward still returns 0 on the x and y axis
I've decided to go with AddForce, but my player still isn't moving with left click. Can anyone help please?
no, it returns the world-space forward vector
which will have non-zero X and Y components if the transform is rotated at all
i said you need a boolean at least if you doing this, velocity overrides add force
How could I use a bool to enable the force?
if you set a rigidbody's velocity, none of the forces you applied matter anymore
In FixedUpdate() method, but I don't think that the result was different when I used Update().
I get input like this (with Player Input component):
private void OnMove(InputValue inputValue)
{
moveInput = inputValue.Get<Vector2>();
}
My movement method is a bit messy, so it might be, that the values are going up and down, so rounding them or something may solve the issue:
private void HandleMovement()
{
if (moveInput != Vector2.zero)
{
if (moveState == MoveState.Standing)
{
moveState = MoveState.Walking;
}
velocityChange = (transform.forward * moveInput.y + transform.right * moveInput.x) * maxSpeed - velocity;
if (positionState == PositionState.InAir)
{
velocityChange *= inAirMultiplier;
}
velocity += velocityChange * acceleration * Time.deltaTime;
rb.velocity = new Vector3(velocity.x, rb.velocity.y, velocity.z);
}
else if (rb.velocity.magnitude != 0)
{
if (positionState == PositionState.InAir)
{
velocity -= velocity * inAirMultiplier * Time.deltaTime;
}
else
{
velocity -= velocity * acceleration * 4 * Time.deltaTime;
}
rb.velocity = new Vector3(velocity.x, rb.velocity.y, velocity.z);
}
}
OOOOF
notably, you're applying force vertically
I shouldve done more research
then overwriting the vertical velocity
All right I fixed it and the animation doesn't work and this appears
Is there any way I can apply a force while setting the RB's velocity?
well, does the Sword_lv1 animator controller have a state named "SwordAnimation"?
StartCoroutine(RecoilAddForce());
if(recoil) return;
rb.velocity = etc.
or something
Looking closer, this is probably fine. You only overwrite the Y velocity if you press or release the jump key.
You're not adding a ton of force, though
AddForce's default mode interpretes the vector as...a force
you're pushing with 50 newtons of force for 0.02 seconds
this is equivalent to using ForceMode.Impulse with transform.up for the first argument
I would suggest using that. It's appropriate for an instant force
rb.AddForce(transform.up * GunKickBack, ForceMode.Impulse);
@rich adder I did try assign it in the teleport class #archived-code-general message
I think i did it wrong
I increased the force to 500 and now it's working but only with every 3rd click
oh, that's 'cos you're checking in fixedupdate
Uh I don't understand 😅. Sorry I am a beginner in Unity
Double click the "Sword_lv1" field in the Animator's inspector.
show me that.
the Down/Up methods only return true for one frame
assign it in the inspector then to be sure
GetComponent only works if the character controller is on same object
Check for input in Update, then act upon that input in FixedUpdate
(or just do this in Update. should be fine for the Impulse mode)
hi everyone. i have problems with connecting my unity to sql. someone please text. its very important
don't cross-post.
It's working!!! Thank you everyone who helped! 🙂
This?
SwordButton is not SwordAnimation
When you call Play on an Animator, it looks for a state with that name
Each rectangle in the animator controller editor (except for those special Entry/Any State/Exit ones) is a state.
i got u
Its already assigned on the player
Theclass PlayerMovement is the one making use of that controller: https://paste.myst.rs/uzp6dk43
a powerful website for storing and sharing text and code snippets. completely free and open source.
you probably want to have two states:
- Idle, the default state
- SwordSwing, the state your script plays
the error you showed earlier isnt even coming from this script
does NPC have a character controller? otherwise no point on doing this
Thats true, I thought I could put the disable controller text you sent me in the Teleport script
https://paste.myst.rs/n0n246fu
a powerful website for storing and sharing text and code snippets. completely free and open source.
No, but I am not able to teleport my player
which one are you trying to teleport mate
Why do NPCs have a CharacterController and a NavMeshAgent?
agent doesnt use character controller
Trying to teleport the Player to one of the chosen locations
I believe you should only be using one of them
I want the player to be teleported when getting close to that npc
so then why is it inisde the NPC script
I am not thinking well at the moment 😅
put the distance check on the player then
Question: Why is the player moving on its own, while the camera is moving, it moves right a few steps.
float verticalInput = Input.GetAxis("Vertical");
// Calculate the movement direction relative to the camera's rotation
Vector3 forward = playerCamera.transform.forward;
Vector3 right = playerCamera.transform.right;
forward.y = 0f; // Ensure no vertical movement
right.y = 0f; // Ensure no vertical movement
forward.Normalize();
right.Normalize();
Vector3 desiredMoveDirection = forward * verticalInput + right * horizontalInput;
// Apply the movement to the rigidbody
rb.velocity = desiredMoveDirection * playerSpeed;```
I see 😅 1 sec I will try and fix that with what Nav told me
No
First Person Story Rich, Puzzle and Mystery game
Right
I believe u dont need to get the Cameras transform
U should be getting the forward of the player controller transform
I'm rotating the camera without the player. Which caused my Movement to not know what forward is.
So ur camera rotates the player correct?
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(AttackTarget.position, AttackRange, enemyLayer);
foreach (Collider2D enemy in hitEnemies)
{
EnemyHealth enemyHealth = enemy.GetComponent<EnemyHealth>();
//int enemyHealth = enemy.GetComponent<EnemyController>().currentHealth;
if (enemyHealth != null)
{
enemyHealth.TakeDamage(Damage);
}
enemy.GetComponent<Animator>().SetTrigger("Hurt");
}
how do i make sure thats not hitting itself
No the player doesnt rotate at all, i noticed that the player rotating is whats causing my player movement jitter.
Oh thats....strange
I fixed it ty
Yeah i know, this seems to be the only method i can find without completely redoing my First Person Controller, which causes more issues..
whats wrong with this? its supposed to fill the tilemap from (1,1) to (5,5) but all it does is crash
RGT im guessing it has something to do with setting the velocity of the Rigidbody
look at your second for
Yea, i'll eventually find it.
crashed 3 times cuz of that
I mean this
@queen adder@rich adderHow about this?
Gives me this error
Yeah i know, it must be something with the Forward and Right vectors.
I would say just use a character controller
Jittering in my experience comes from setting a camera on a rigidbody
Your also doing work arounds for what should be a simple system
@plucky vapor show the whole code
For both classes?
SI
Yeah i used a character controller, which worked, but removed my ability to interact with rigidbody objects.
a powerful website for storing and sharing text and code snippets. completely free and open source.
a powerful website for storing and sharing text and code snippets. completely free and open source.
Yea, there were objects that had rigidbodys, and if i walked into them, they wouldnt budge.
CharacterControllers have a collider? There shouldnt be a reason that didnt work?
Again abdullah
Why does ur NPC have a character controller
Wait, I thought I removed it?
1 sec
Oh no when I start the game, the animation plays once. How to fix it???
When I have "transform.up", my player gets pushed upwards. But when it's "transform.right", nothing happens. Anyone know why?
It says playerMove was null
what is your gizmo set at for forward
You are probably overriding your X velocity somewhere?
FixedUpdate
Is there any way for me to have a simple save system that saves all the scene?
And like what Dalpat said ur playerMove field isnt set to anything
I'm new to Unity, but I think in FixedUpdate??
What do you mean by save all the scenes?
It's a 2D game. The red arrow points to the right
Yeah thats it
Usually you'd have some specific data that you would want to be saving from each scene, if any.
Is it possible for me to add force while having the X velocity there in FixedUpdate?
maybe use a bool
How do I fix that?
Okay, I remember you sent this to me earlier
StartCoroutine(RecoilAddForce());
if(recoil) return;
rb.velocity = etc
I will try that
Yeah, that's a reasonable option
I'm not sure where to add it tho
U set it in the inspector....
i have lots of Instantiated objects that i would need to save and later load.
That will prevent you from changing your horizontal velocity until the coroutine is done and sends recoil back to false
make the bool = true while its doing AddForce impulse in coroutine
Another option is to just move your velocity towards what the player wants, instead of instantly setting it
rb.velocity = Vector2.MoveTowards(rb.velocity, new Vector2(Horizontal * speed, rb.velocity.y), Time.deltaTime * acceleration);
MoveTowards moves from the first vector to the second vector
but only goes as far as the third argument
You could also reduce acceleration right after shooting
so you have a brief moment of low control
Did that, still error @ivory bobcat @queen adder
Essentially, I want to make a force that will push the player backwards from whereever their gun is facing to simulate recoil
Read what the error says
1 sec
Whos throwing the Null exception
NPCTeleporter on line 47 has an unassigned reference you're trying to use
You gotta read what the error is saying
I have a top down camera, but I need to dynamically bind it to a max area so the player can not pan away too far. How can I set a bounding box where it cannot escape? And this needs to be expanded in all directions during runtime
I am trying to, my migraine is just very strong 🥲
I thought I set it correctly
Is it gonna' be a rectangular area?
U have to set it in the Inspector of the NPC
@swift cragYeah
If so, consider Bounds. https://docs.unity3d.com/ScriptReference/Bounds.html
You can ask for the closest point, and also grow it to include new points.
Cinemachine^^
@swift crag ?
Oh yeah, Cinemachine has components for this, doesn't it?
I can record it if you don't understand what do I mean
Because the default state plays your sword animation.
Sorry, but I'm not sure I understand how I can implement this code?
The main camera might have a method for bounds?
But i know cinemachine has a Component for it
RecoilAddForce would be an IEnumerator method.
@summer stump@queen adderYESSS IT WORKS NOW!! Thank you guys a LOT for the help with this!
@misty obsidian you only have one animation
So the Animation player plays that one animation
IEnumerator Shoot() {
recoil = true;
yield return new WaitForSeconds(0.5f);
recoil = false;
}
something like that
Have you ever used coroutines before? I don't know if I'm using words you don't know about here :p
Nope, but I'm learning a lot haha
When you do StartCoroutine(Shoot()), you run the Shoot method
It runs until it hits a yield, then it pauses and returns an enumerator
StartCoroutine tells Unity that you want it to check on this enumerator every frame (by default)
So every frame, it asks the enumerator to please continue
What's an enumerator?
and the method resumes until it hits a yield
It's something that can give you a sequence of values, one at a time.
Haha
Have you ever used foreach? If so, you've used enumerators.
Just with some nice pretty syntax on top.
Oh yeah
you could alternatively just do Invoke("Method Name")
I've used invoke before
that sends a message. different story.
Invoke("Method Name" , 0.5f)
Ah, I see what you mean
If ur just doing a timer Invoke is fine
You could achieve the same goal, yeah
Just so its simpler to understand for D&M
So this method produces an enumerator. It gives you a WaitForSeconds as its first value. When you ask for a second value, it signals that it's done.
Coroutines are confusing to learn at first
When Unity gets a WaitForSeconds, it waits for however long you say before asking for another value.
can agree
I'm not sure what I'm meant to put here now. I tried putting AddForce but it didn't work
I think they're pretty simple if you don't treat them like magic
I used to think they were magic
multi-threaded, running concurrently, ...
Yes, very haha
Bah. My internet went out
how can make sure my items in my shop can't be bought after i buy them even after restart the game?
https://hastebin.com/share/wamijizixu.csharp (BuyItem)
https://hastebin.com/share/ufewusujib.csharp (GameManager)
You would have to save the state of the Shop
I think the idea was to use those three lines of code in various places. The recoil variable is used to stop you from setting the velocity based on player input if you just shot
Can someone help me understand the fundementals of a saving/loading system, in my game i have lots of prefabs that get spawned, and each have different variables and positions that would need to get saved, how would i be able to even start to go about such a thing.
Welcome to one the worst parts of Game Development Save systems @sterile radish
Serialization can be a real bugbear
Oh I see, so I wasn't meant to use those 3 lines together like that?
is there any other way besides using .json?
Its complicated just start with a tutorial on youtube
Theres a bunch @sterile radish but they each have there own benefits and disadvantages
I think the code given to you was meant to be used in a few different places.
ah alright, the way im doing it now is adding all of my bought items into some "boughtItems" list and saving and loading that each time i go to the shop
Okay
That sounds fine?
This is what I've got now. It's not working 😦
I’ll be back in a few minutes. Fighting Comcast right now
I dont know how list get serialized actually?
i think i might be doing something wrong tho cuz it works when im running the game but when i close it and open it again it goes back to its unsaved state
You should check if the recoil bool is true before starting the Coroutine @west sonnet
Do u have an actual save system?
If not then ofc the scene is going back to its default state
Ofc
yaaay, working internet
Nice welcome back
This code will start the coroutine, which will set recoil to true
then it'll immediately return by recoil is true
so that's definitely not it!
I shouldve explained it more detail ^^^ but yeah
You should move if (recoil) return to the FixedUpdate line. That will prevent your velocity from being set while recoil is true
I defined the recoil bool to be false. Then when left click, it starts to coroutine which turns the bool true
So the coroutine sets recoil to true, waits half a second, and sets recoil to false
Right?
Right. And your current code is then refusing to apply force if recoil is true
hence, no force
Ur setting it to true then saying if it is true then dont addforce
Wait, where should " rb.AddForce(transform.right * GunKickBack, ForceMode2D.Impulse); " be?
Wherever you want to apply the force.
I think it's in a reasonable place right now.
You want to apply the force when the player clicks the left mouse button.
is there code to clear all text from a json file?
Cant u just write to it and do file.text = " "
File.WriteAllText
So this is my code right now, and I still don't get why it's not working 😦
are these expressions the same?
public List<GameObject> SummonList = new();
and
public List<GameObject> SummonList = new List<GameObject>();
follow it line by line
Explain to me what FixedUpdate does.
i can send the script for buying items too if you want
https://hastebin.com/share/zidijuyeqa.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you are overwriting the velocity in FixedUpdate so your knockback force is getting canceled out
im trying this but sometimes when i do it it adds the new data that i want to overwrite on top
also use the bool for startcoroutine too
so. you dont start it twice while its busy
Yes. C# can infer the type for new().
I would NOT use playerprefs for a shop system
thank you, good to know
oh okay, what would you suggest?
how so ? code only does what you tell it to
How many items are in the shop?
six items
so does the function always overwrite all the data in the file?
Share the whole class
okay
it writes whatever you pass inside
File.WriteAllText(path, "");
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Fixed update sets the X velocity value?
That's what the first line does, yes.
And what does the second line do?
On line 29 roshi you dont set anything to what playerprefs returns
It stops the code from running unless recoil is true? Otherwise it'll repeat setting the X velocity value?
No. It returns from the function if recoil is true.
If recoil is false, the second line does nothing. The function then exits, since we've reached the end anyways.
The second line does nothing.
The RecoildAddForce function?
It returns from the function it's inside of.
You sound confused about what code is running when.
I am lol
why would return affect another function its not inside of?
oh oops didnt notice that lol. idk if this is the best way to do it but should i just split the bought items array again since i joined it when i was saving it? then check if it contains that same item id?
Personally i would use a dictionary
Just for simplicity sake
Dictionary<Item, bool>
Just request the item from the dictionary and check the bool to see if its been bought or not
You can set the bool in playerprefs by using ints because for some shortsighted reason it isnt in playerprefs
oh okay and would this replace the boughtitems list in my itemmanager script?
I know i threw alot at u and im sorry for that
nah all good bro
no but i could try
Save systems are complicated
You could just try ur original method of getting and settings strings
figured out the problem thanks
what was it
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(AttackTarget.position, AttackRange, enemyLayer);
foreach (Collider2D enemy in hitEnemies)
{
if (enemy != gameObject.GetComponent<Collider2D>())
{
MultiplayerHealth enemyHealth = enemy.GetComponent<MultiplayerHealth>();
//int enemyHealth = enemy.GetComponent<EnemyController>().currentHealth;
if (enemyHealth != null)
{
enemyHealth.TakeDamage(5f);
}
enemy.GetComponent<Animator>().SetTrigger("Hurt");
}
}
why does this still damage me instead of the other player
are the layer setup correct?
Check that
i messed up my editor script and accidentally collected all the data in the game twice
Perhaps you have multiple colliders.
Since a scriptable object is an asset, how are you to save a list of them to files to read later on?
The player is in the enemyLayer?
is there any way to make an input listener that gets the name of the input you press?
its in that layermask yeah
the layermask consists of 2 layers player and enemy
Check the Gameobject instead of the collider
if (enemy.gameobject != this.gameobject)
in risk of rain 2 when i changed the binding of a couple things the name went to ???
how do i get the input like that where it displays the name of the controller button i pressed
thanks
This works for Keyboards apparently if u have controller support youre gonna have to do some more research sorry lol
Oh right no gifs

I actually have no idea
That only happens when ur next to and edge?
still does the same thing
it only does it though if it hits the other person
im gonna try adding unity as a non steam game to see if steam will put the input on it
Share ur code pancake
Seems like you are only setting isGrounded to false when you jump
You should at least do it when you exit collision with ground
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(AttackTarget.position, AttackRange, enemyLayer);
foreach (Collider2D enemy in hitEnemies)
{
if (enemy.gameObject != this.gameObject)
{
MultiplayerHealth enemyHealth = enemy.GetComponent<MultiplayerHealth>();
//int enemyHealth = enemy.GetComponent<EnemyController>().currentHealth;
if (enemyHealth != null)
{
enemyHealth.TakeDamage(5f);
}
enemy.GetComponent<Animator>().SetTrigger("Hurt");
}
}
@queen adder Or use Physics.CheckSphere or some other physics query to check if you are grounded instead
Share the entire class
public void TakeDamage(float damage)
{
if (playerController.isBlocking)
{
damage = damage / 4;
}
currentHealth.Value -= damage;
animator.SetTrigger("Hurt");
Debug.Log(damage);
if (currentHealth.Value <= 0)
{
Die();
}
}
this is the other function thats called
You can ask for a display string for the control that triggered an input action.
context.control.displayName for example
You can also ask for the display string for an input binding
it aint pretty but here
https://pastebin.com/YwQMktJ3
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Are any of the attack methods you have called ?
yeah
Is the player actually taking damage or is the animation just playing
they take damage
Does the enemy get hurt?
i print it as a debug 1 i have a health bar go down aswell
no
This just gets more confusing
Add a debug.log in the foreach
Does any other Gameobject have the ability to attack?
the thing im trying to deal damage to
Put a debug.log in the foreach loop
what should it log
before or after the if
so it hits the other thing then itself then deals damage
yeah
That means the enemy is calling the Attack Method as well
I keep getting serialise and deserialise confused, which one is which?
serialize -> turn your objects into data
deserialize -> turn your data into objects
serialize to save, deserialize to load
@amber spruce any luck?
To "serialize" is to turn something into a series of bytes
yep i fixed it thanks
Was it what i said or was it something else?
What's the correct way to access a component existing on another object? Because this doesn't work 😅
