#archived-code-general
1 messages · Page 306 of 1
So what would be problematic about using the Canvas or UIToolkit for your UI? Do you need to handle this "4th wall breaking" from outside your Unity game?
for it to be a virus it needs to send data to the developers or cause damage to the sevice
but the ide is similar yea
i use the word virus here very vaguely, theres nothing to distinguish between a program who wants to mess with someones other apps compared to a malicious attack
Anyways you should describe what you're trying to do, "mess with other apps" could mean a lot. There really isnt much you can do from outside besides like kill the process, in which case users will instantly refund your game
Assuming the game gets approved for uploading, something like that would likely be detected by whoever reviews your game on the platform you upload, and could violate developer contracts for that platform (but that gets legal, which is a whole other thing)
i dont think ill share it publicly
still, theres nothing you can really do. You cannot just connect to someones chrome or discord and do anything
how does this work?
https://docs.unity3d.com/ScriptReference/Application.OpenURL.html
Honestly though, it sounds like what you want to do is less of an intention for game engines
¯_(ツ)_/¯
can I use this to open .vbs files? they are a really easy way to make messageboxes
You can use the C# Process.Start to start any kind of .exe. if that exe happens to be a program that opens .vbs files, you can probably pass the file path as an argument for it to open it.
Though, the best you can do to get any data back is wait for it's closing code. Unless it's an app that you wrote yourself. Then you might be able to establish some kind of interprocess communication.
but I cant use process.start() in unity
Why not?
idk it says its not a function
Maybe need a namespace
What says that? Are you using the correct namespace?
Do you have IDE configured correctly? It should suggest you the correct namespace...
VS automatically puts the namespace there for me
I think I got a problem here after the changes, when Player 1 got all hits and dies, it doesn't player the death animation and instead instant teleport to the checkpoint in a weird away. Even though player 2 is still working, I just don't know why it works for player 1 but not player 1
how could we possibly know without seeing the death script
https://gdl.space/caqodelama.cs this is destroyonexit, which is working perfecly fine
https://gdl.space/bulividehi.cs this is the checkpoint
https://gdl.space/kiticesofi.cs and this is how much damage you took
they all worked before
that takedamage method 😵💫
before what? what did you change last
this
the commect i mentioned to here
also I think it was because I accidentally deleted all the animations on player 1 so that I have to redo it
only you should know for sure then, just get back to how it was
I did, and everything is working that the players have like the same thing, but instead when player 1 dies, no death animation, respawn in a weird way and the health bar doesn't go back to full health
Do you still not have version control after all those recommendations?
version control?
also, what is the need to create a new player object each time?
Git, or Unity Version Control
this code is honestly a chore to glance over, so much repetition
huh ? why is it in the checkpoint script?
everytime the player dies and one life lost, but loses all lifes, it becomes gameover
yeah but you have checkpoint code inside a OnState exit of animator? seems weird to rely on animator at all for that
unity
why is it weird?
what is it meant to accomplish ?
Are you saying you are using Unity Version Control? Then how did you accidentally delete the animations? Just don't commit that change
I was going to make a new controller for something else, but accidentally deleted player 1's controller's animations
You're not understanding what I am saying. If you are using version control, that doesn't matter. You could just either not commit that change or revert it
It would not be possible to accidentally delete something in that way
to Player 1's animator with all the animations...? I don't know ,it's been like over a year ago
what is unity version control?
Oh my god....
Why did you respond like this:
#archived-code-general message
If you didn't know what it meant!?
Google it. Get version control like now
how do I get the folder path of assets?
I was thinking of using Unity for a 3D human pose estimation system, to visual a squash game in a 3D interactive environment, has anyone ever done anything similar for a different sporting game, also could I embed my program or the results of my program into a web application? I've never used unity before but am a confident programmer.
I can barely get it because I don't remember my unityid and password
Use git.
And a password manager
hmm.. I need to get help from my dad first for this like registering and all that
Application.dataPath
the death animation is working right now, but the teleport thing, and that I can't move and the health bar
as I moved it a bit higher, I noticed that I'm completely frozen, so unmoving
is there any easy free solution to implement text to speech on windows, ive tried using LMNT and using MRTK, MRTK straight up didnt work and LMNT was very buggy and pretty well broken
could I get some help with this?
UnityAction nextEvent;
void SkipLine(DialogueLine line)
{
//do stuff
}
void Start()
{
nextEvent += () => SkipLine(line);
}
output:
Object of type UnityEngine.Object cannot be converted into DialogueLine
I've tried adding that lambda directly to an event as a listener, tried adding another event inside the script, and adding it to that, then adding the event to the event I'm trying to listen to etc. I'm lost at this point
the error points to UnityEvents.cs
DialogueLine is a ScriptableObject too
Share the whole error details
Is there a good way to find the object that is closest to a point? Visualize it like making a sphere at a point that expands until it hits an object.
I could make my own crude implementation, but I was wondering if there's a built in way of doing this.
An overlap sphere and then sort/search for the closest object
Thank you
I've fixed it by just making a variable to store the next dialogue instead of passing it through the event
I've been hitting my head about this problem for the past few hours. Can anyone offer advice? I have a Dictionary<Vector3, Vector3>, and calling ContainsKey() acts oddly sometimes. Using breakpoints, I can verify the Vector3 is in the dictionary, but ContainsKey() returns false.
Floating point comparison is very unreliable. You shouldn't use a Vector3(that is 3 floats) as a key.
Hey yall, im having some problems with rigidbody.addexplosionforce
I'm making a grenade in vr meant for launching yourself. it works just fine on every other object in the scene, but not the player. What's weird is I have scripts on the player that allow jumping or moving by adding force and work just fine, but force cannot be added via the grenade.
I also tried making my own add explosion force with just a more complicated addforce function but to no avail. I've also tried switching forcemode to velocity change and still no effect.
The rigidbody is not kinematic at any time, and yes I have tried increasing the grenade's force significantly, as in like 10000000. the radius is also just fine, it's moving objects farther away than the player
At a guess something on your player controller is counteracting the force added by the grenade. you might like to consider passing the required force to the player and letting him handle it itself
i tried disabling every script exept the ones strictly necessary (like moving the hands and head for vr) on the player controller and still nothing happened so i will try to pass it to a new script on the player and see what happens
When I was building the implementation of the Dictionary, I wondered if that was a problem. I read that the unity Vector3 struct overloads the == operator to check the squared magnatude of the distance between the Vectors, instead of checking xyz cordinates for exact equality. Decompiling the Vector3 struct revealed the margin of error to be 9.99999944E-11f. So yes, I'm going to have to make my own Vector3 implementation. : (
There's no guarantee that dictionary uses == for comparison.
As for your problem, I think you're approaching the problem from a wrong angle. Instead of reimplementing a type that is not meant for comparison, use a type that is meant for comparison. Like Vector3Int.
what do you even need a dictionary of vector to vector for?
you don't need your own Vector3 implementation. It's much easier to write your own comparer for the dictionary
well i figured out my problem
i made my own script attached to the player and it still wasnt working which was very confusing
it just hit me that the player rigidbody never existed in the list of rigidbodies in the radius
because i totally forgot that the exploding object's layer does not have collision with the player as i dont want items getting pushed away while youre trying to pick them up
Hopefully that will teach you to not make assumptions and actually check everything first
this is my image, which contains the following children. How do I, in the script, make Player(1) and it's children not be rendered?
I have tried set active, get component and a few other fixes, furthermore when I toggle the eye icon in hierarchy view in editor, the image has it's rendered turned off only in editor, not in game view? Please help.
setting it to inactive will definitely not render it in both editor and gameview
what are you doing?
all you need to do is just get a reference to Player(1) and set it to inactive using SetActive
exactly what i've done.
toggle the eye icon in hierarchy view in editor, the image has it's rendered turned off only in editor, not in game view
That's what it does, yes
I see.
then it should work
ive used a public GameObject and references Player(1) to it in inspector
let me try again
nvm turns out i made a stupid mistake
thankyou though
So I'm sort of a fan of read only data objects. If I want to make these properties visible in the inspector, is this really what I need to do?
just to correct a misconception, that does not expose the properties it exposes the automatic backing fields of the properties. You will probably also need a parameterless constructor
I am aware it exposes the backing field.
Honestly even after all these years I'm still not exactly sure of the interaction between constructors and objects unity serializes.
almost all serializing systems use Activator.CreateInstance to make an instance of a given class, this requires the class to have a parameterless constructor.
Now any class which does not define a constructor will have that by default however as you have declared a parametred constructor you also need to declare a parameterless one yourself
And what happens without a parameterless constructor?
serializing/deserializing will not work
Will not work as in nothing will show, will not work as in stuff wont get saved, or will not work as in stuff gets... freaky?
there is a fallback, Formatter.CreateUninitializedInstance but I doubt Unity uses that.
will not work as in will throw an exception of just will not do anything depending on how it is implemented
🤔
It might just be magic?
does it actually save anything if you make changes?
which is internal not seriaized
Well changes I make to the values in the inspector are maintained.
Closing Unity and reopening also maintains it.
ok, so they are using Formatter not Activator
I think the wildest thing I've done is I had a serialized class that took in a Func, which I defined in variable initialization.
And it worked.
Like this works.
It has nothing to do with serialization, so sure
Every variable initializer will be called as usual; and if the field is serialized the serializer may come along afterwards and replace the value that was there
Is there a channel for code review?
@dawn nebula As I suspected they are Using Formatter which does not require a constructor. So..
public class NewBehaviourScript : MonoBehaviour
{
public Test test;
// Start is called before the first frame update
void Start()
{
test.Print();
}
}
[System.Serializable]
public class Test
{
public int x;
int y = 2;
public Test(int z)
{
x = z;
}
public void Print()
{
Debug.Log($" {x} {y}");
}
}
outputs
but if I add the paramaterless constructor to Test the output is
So y isn't getting initialized properly?
exactly, because y is initialized when the constructor is called
how does X even get a value of 1?
I set it in the inspector
rule of thumb, if you ever add a parameter constructor to a serialized class always add a paramaterless one as well
In general or just with Unity?
in general
Why?
because most systems will not use the Formatter fallback and so will throw an exception
Damn. I like the guard rails made by constructors.
Anyway, can I toss a short script (~70 lines) in here for review?
Yes, on the specific site
Which specific site? Hastebin?
!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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is a generic timer class that I use.
I just subscribe what I want to happen to the OnDone callback.
and tick the timer in Update
this
Target = Mathf.Clamp(newTarget, 0, Mathf.Infinity);
is a very bad way to say >= 0f;
also I would check if newTarget != Target
not too sure about your variable names either
also this
public bool IsDone => Current == Target;
is very dodgy
I know that direct float comparisons are bad, but with Current being clamped to 0 and Target, I don't think it can fail.
I would be surprised if you ever actually use any of those first 3 events too
yes it can if Target is not directly divisable by all the accumulated deltas
this seems like something you create for the purpose of a small use case, not something thats passed around to be used by many scripts
The main use cases are things going off on OnDone, and updating visuals.
Like for example a UI timer.
tbh it looks like a sledgehammer to crack a nut
LOL
i could definitely see some use out of a basic timer because i do find myself doing the classic
time += ...
if time >= something, time -= something.
But yea this is overkill
I havent observed the timer ever miss. Are you absolutely sure doing a clamp between 0 and target isn't enough for a safe Current == Target comparison?
missed that. but you dont need the Clamp if you just do
public bool IsDone => Current >= Target;
I guess that's fair, but current will not (or shouldn't >_>) ever exceed target.
if you use Time.deltaTime as your delta you can guarantee it will be
after the clamp
i dont think it really matters if it does in your case. You could just have the property for current return target if its larger. Clamping between all this isnt needed
if you take the clamp away. why clamp something that doesn't need to be clamped.
this is a typical example of a CS Student implementation of a simple problem
it's just a question of experience, no offence intended
It would be a lot simpler if this class was something that could exist on it's own, without needing to call Tick().
But then you would be somewhat recreating a small portion of what tweening libraries do
Right now, this code doesnt really make anything easier for other code
Awkward moment when I'm self taught and in my mid-20s but whatever I guess.
I kinda like being able to directly feed in the delta.
If I wanted something running by itself I could do something wild like a pool of gameobjects that hold timers.
but are you an IT professional, when I was in my mid-20's I had been a professional designer/developer for 7 years
I create visualizations of MRI scans within Unity as my job. So a professional for about 3ish years.
I'll be honest though I do have a tendency to overengineer.
Overengineering is no bad thing when you are dealing with very sensitive data, so I cannot blame you for that
Nah you know what it's my bad. The CS student comment irked me and I pushed back. It's all good.
I was recently involved in a game jam, and I'm going through some of the general utility scripts I wrote and cleaning them up for future use.
This timer was one of them, and I found the pattern of just subscribing to the OnDone event and calling Tick to be pretty clean.
it's the opposite of clean in my eyes. Why did you make it a poco class? The problems I have with its design all stem from that
my 2 cents (if you wish). Try to wear 2 hats, one for app dev (which is what you are doing for work) and one for game dev. IMAO mixing the two rarely make good bed fellows
Ya don't get me started on the amount of "analysis paralysis" I've gotten myself into with game projects.
Mind elaborating?
You have a weird half-serialized mutt class that can only be used if it's tightly coupled to whatever thing uses it. What is your justification for making it a plain class instead of a MonoBehaviour? It's built in a super weird way
In the context of the jam I just wanted something quick, but now I'd like to remove all the Unity dependencies. A concept as simple as a "timer" didn't make sense to be Unity specific, so I just worked with a regular class.
Plus the game I was working on needed controlled pausing. The timer had a Tick method that took in a delta. It seemed weird to extend off a class that has Update.
If I wanted a Unity implementation I could always wrap it in a Monobehaviour and hook up some UnityEvent callbacks to it 🤷♂️
hmmm yagni is your friend in a situation like this
By the end of the Jam I was setting up timers like this.
Running them like this.
And setting them up in the inspector like this.
where half of the timer is set up in the inspector, and the other half in code? That's one of the reasons I don't like your setup. Look at the snippets you posted. You apparently have a timer script, except it's three sub-timers and a GameManager in a trench coat with its fingers in day/night, generating "offers" and has something to do with the economy
and you got forced to mash it all into one place because you made your timers plain classes so the design is awkward
I don't think there's anything wrong with behaviour (what methods are called) being defined in code and inputs (like duration) being defined in the inspector.
As for what this class does, it's my "GameDirector". The GameManager contains the entire state of the game. The timers go off when they need to, and call functions which manipulate the state within the GameManager.
I've done freakier things.
can anyone help me with this error message?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class NewBehaviourScript : MonoBehaviour
{
private PlayerInput playerInput;
private PlayerInput.OnFootActions onFoot;
private PlayerMotor motor;
// Start is called before the first frame update
void Awake()
{
playerInput = new PlayerInput();
onFoot = playerInput.onFoot;
motor = GetComponent<PlayerMotor>();
}
// Update is called once per frame
void FixedUpdate()
{
motor.ProcessMove(onFoot.Movement.ReadValue<Vector2>());
}
private void OnEnable()
{
onFoot.Enable();
}
private void OnDisable()
{
onFoot.Disable();
}
}```
heres the code
Please, don't cross-post
we've seen this one before. Search this discord for PlayerInput.OnFootActions onFoot; and you should find the solution
@knotty sun Alright lay it on me. How bad does this look?
Bad, for one thing using all the anonymous methods you can never unsubscribe
Dont worry about that part.
I worry about everything, it's in my nature
damn
without context of the use case it's difficult to say if this is sensible or not but I see a lot of garbage being generated there which I do not like
You can unsubscribe none of them
Beautiful isnt it?
If the blood from my left eye is the sign of seeing something beautiful, then yes, it is indeed beautiful
If you don't want to unsubscribe them, consider using events in order to add non-permanent listeners
myClass.myEvent.AddListener(() => ...);
If you hover over the => it should tell you what is being captured in all those
Or maybe I am thinking of the wrong place to hover, but something in there should tell you
For the game jam I wanted to try complete separation between game visuals and data management. What you're seeing is all the managers having callbacks when specific things occur. The eventHub is a PubSub-like structure, so an event gets generated and sent off to any listeners. The visual side has some top level manager that listens to these events and calls appropriate functions.
tbh I absolutely hate anonymous methods and when I see new instances being created for each invocation it makes my skin crawl
please help me with this problem i havent gotten a working answer half of this week
If it means anything, the PubSub can take in structs, which I'm pretty sure are much better for these types of short lived, immutable, small data containers.
I just... didn't make them structs 🙃
just means you would be overloading non managed memory rather than managed memory, less gc to be sure but, in effect the same clean up operation required after each invocation
Please properly explain the issue and share related code if you want to be helped
This video explains nothing but a possible issue with rendering
Now you may be asking. Why did I use PubSub instead of just making a high level script whose job was to tie these callbacks directly to the view? Idk it was a good meme at the time.
Does it make an big diffrence if i use the normal 3d and the tutorial is made in URP?
only in terms of the shaders you will need to apply to any materials used
Okay
I can't seem to find URP anymore
you'll have to excuse me for being very, very old school, I literally worry about every single bit of memory I allocate and every single clock cycle my code takes to execute
bro computers have like billions of memories nowadays its fine
That's why every triple A game nowadays is 100 GB minimum
no it is not because everyone down is being profligate with them with leaves the end user with a very bad experience
it's attitudes like this that has led us to the current dire straight of operating systems implementations
All good though. I know your type. I wouldn't have done this set up if the game was more real-time. The game state doesn't send out updates unless the user clicks something or one of those timers go off.
So realistically those event objects are being generated 0 times per frame until one of those things go off. In which case it's probably around 2-4 events per action.
buy more ram
benefit everyone, write better software
Perhaps you've missed the first part of their sentence.
as you can see the tile doesnt swap when i jump
but the boxcollider does enable and disable
so i think this is an issue in the rendering
It does. The anonymous methods only capture the eventHub. When the GameManager dies it'll take all the other managers with it, so technically no issue 🙃
They're regular C# events, not UnityEvents.
how can i fix this problem
You say "as you can see", but you just sent a video of you clicking a button on some website
Unity hub isn't installing the windows build tool for some reason on my machine
Could someone zip and send the WindowsPlaybackEngine for unity 2022.3.22f1 to me?
you can find it at Unity Hub/Editors/2022.3.22f1/Editor/Data/PlaybackEngines/WindowsStandaloneSupport/
Either that or tell me where I can find a download for it online
no way i made that mistake bruh
but this is the real video
when you build your game, if you enable the "Development Build" checkbox, you will be able to see errors show up in a console window on the game. So, maybe do a development build to make sure you aren't getting any errors.
do i need any of these
there arent any errors except a different one because its trying to load the next scene which doesnt exist
Seems like a weird issue with SwapTile, try calling redMap.RefreshAllTiles() and blueMap.RefreshAllTiles() at the bottom of your FlipTiles method
Not really sure why it would be messing up in the build though
I'm trying to make a minimap sort of thing using an orthographic camera, and just 15 minutes ago it was working. But now... I'm running into an error I don't understand XD
In the video you can see that I have an orthographic camera that in attached to a render texture, which is then fed into a raw image in my UI, as the minimap display.
But when I run my game, I get hit with a lot of debug logs saying that my camera isn't assigned, although... you've seen it is. And the WEIRDES part, is that I can STILL move the camera by dragging on the minimap display, meaning that it IS assigned. So when I'm not touching the minimap display, why is the camera "not assigned" in the eyes of the script?
Seems like you maybe have 2 copies of the script in the scene by accident?
Try putting Debug.Log($"Running from {gameObject.name}!", gameObject); in Start of your script
I found a download but it's in a pkg so idk what I'm meant to do with it lol
If you mean the one I closed, no that was from my test project where I first implemented the minimap.
And I used the debug log you sent, it just says "Running from MiniMapController" which is just the name of the script. I looked for any other objects that have that script attached, and there's only one. So idk anymore XD
It's just so weird because I have it check if the camera is null. If it's not, then say "MinimapController: Update: Entering HandleZoomInput!", which when I interact with the UI image that has the images created by the minimap camera, it sends those debug log. And as soon as I stop interacting with it, it goes back to saying it's null
And it's so annoying XD
The log I recommended should have printed the name of the gameObject that the script is on, not the name of the script. And the point of the log is to see if it logs more than once. You could enable Collapse mode in the console to make it easier to see. If you do that, and it does really only log once, then I would be suspicious of the fact that your miniMapCamera variable is public, meaning that any other script in your entire project could modify it.
WAIT
i will try this out
I just noticed. There ARE two debug logs. But... how? The first one is the object I attached the script to. The second one is the literal script...
And no other scripts are modifying this one because I just implemented it
I haven't had the chance to do anything else
Why don't you scroll all the way down in the list of components on both objects?
Already found the issue
If it isn't there when the game is not running, then it must be getting added at runtime
private static MiniMapController _instance;
public static MiniMapController instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<MiniMapController>();
if (_instance == null)
{
GameObject go = new GameObject("MiniMapController");
_instance = go.AddComponent<MiniMapController>();
}
}
return _instance;
}
}
This.
I guess I have to find a new way to access variables in a seperate script.
Any ideas? XD
Also thank you so much
That part of the script was the reason it was running twice
Maybe you could explain where that code you just sent is (which file it's in), and what other code uses the instance variable
but, generally speaking, I just wouldn't recommend creating a new gameobject and adding a component there. You need to assign variables in your script anyways, so it would be uninitialized if you just AddComponent and do nothing else with it.
I would instead just ensure that it's in the scene. If it's not, I would throw an exception or log a warning so that you know you have made a mistake by forgetting to add it to the scene
But still, I am not entirely sure why this caused another script to get added? Shouldn't the FindObjectOfType been able to find your script in the scene, and therefore the second if statement wouldn't have ran?
Oh sorry
That code snippet is just below my variables
https://pastebin.com/ribWvX3Y
And the reason it's running twice is because it's attached to a gameObject and already instanced. And then that code snippet is then creating a second instance which was running all the errors.
Now if I remove that snippet the problem goes away, but I can't reference any variables in this script in any other scripts.
I tried attaching the script to an empty objects, like most of my other event scripts, but I can't figure out how to handle onDrag events, etc when it's not attached to the object with the events itself
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.
If it's already instanced, wouldn't your FindObjectOfType call assign _instance and therefore not run the second part of the snippet?
No it still runs the snippet because they're different names. The first instance that is created is the name of the object the script is attached to, "NewMap". The second instance it's creating is "MiniMapController" Which doesn't exist yet, so, it creates it
FindObjectOfType finds the component type, not the gameobject name
I think I'm just going to attach the script to an instance of an empty object, like my other event handlers, and make the image it was previously attached to just send events with "Even Trigger"
Oh yeah. Well then I have no clue why it's creating a second instance XD
But it is
Well, me neither.. it shouldn't be, so all I can do is guess that you are trying to access the instance variable from another scene, before the scene with your "NewMap" object is loaded. But I don't know anything else about your project, so not sure if that could be an issue or not (from the looks of your video, it isn't the issue)
public void GenerateCustomizationOptions(ShipData shipData, List<WeaponObject> weaponObjects, List<ComponentObject> componentObjects)
{
Debug.Log(weaponObjects);
List<string> weapons = weaponObjects.Select(x => x.name).ToList();
weapons.Add("Unarmed");
Debug.Log("Weapons: " + weapons.Count);
List<string> components = componentObjects.Select(x => x.name).ToList();
components.Add("Unarmed");
ClearExistingOptions();
//Generate Dropdowns for Repeater Mounts
for (int i = 0; i < shipData.repeaterMountCount; i++)
{
CreateDropdown("Mount " + (i + 1), weapons);
}
for (int i = 0; i < shipData.componentCount; i++)
{
CreateDropdown("Component" + (i + 1), components);
}
}
I am trying to make a dropdown but for some reason my lines 4-8 will not make a proper list. If I don't include the add method (line 5) it will send the object RR-01 as an option, but with the add method, it removes everything and only sends that Unarmed string to the list. Does anyone know the cause for this?
@rapid stump Try calling FindObjectOfType<MiniMapController>(true); instead. This will try to find inactive objects as well. Maybe you are disabling it on the first frame or something.
Yeah... sadly that's not the issue. What is the issue? No clue 🙂 But at least you helped me find the cause of the problem, and now I'm just setting up the Event Triggers so I can handle the interactions with the map using an empty object instance of the script
Ooo, maybe. Let's see
gasp
That fixed it
You're a god lol
How are you creating the dropdown? This sounds like the relevant part
Log the contents of the list?
tried this and it gives me a very vague answer. Or there is just one item in it
This is the creation code:
private void CreateDropdown(string label, List<string> options)
{
GameObject dropdownGo = Instantiate(dropdownPrefab, gridParent);
dropdownGo.name = label + " Dropdown";
TMP_Dropdown dropdown = dropdownGo.GetComponentInChildren<TMP_Dropdown>();
dropdown.ClearOptions();
dropdown.AddOptions(options);
dropdown.RefreshShownValue();
TextMeshProUGUI a = dropdownGo.GetComponentInChildren<TextMeshProUGUI>();
a.text = label;
}
You can log the the contents of the list by doing
foreach (var element in list)
Debug.Log(element);
OMG, you are calling this INSIDE the for loops
yes. It generates them like so
Only item is unarmed. Gonna check the objs
Figured it out. Seems I will need to check EVERY little thing of my program when using Unity Version Control as it reset the Weapon Objects list and so nothing would be sent down the chain
still doesnt work
OK so basically I had a particle system that spawned fireflies randomly around the terrain at night. I changed the terrain about a week ago (completely new terrain), and now I don't see the fireflies spawn. There is a prefab called Fireflies, a placement generator script I found online, and then code that turns it off during day and on during night. First screenshot: placement generator script component added onto a scripts empty object. I messed around with "Height of check" and nothing changed. Second screenshot: for loop that plays fireflies at night that worked before, but now it is not even giving me that debug log. Third screenshot is the full placement generator code I found online (I tried searching for it again but could not find it). Im at a complete loss, any ideas?
i tried deleting the library folder and the problem still continues
it could be any number of those parameters in the PlacementGenerator that affects whether or not it fails to place them. The height, range, and positive / negative ranges all affect where it tries to check.
yeah update: changed "height of check" again, this time to 20, and now the debug log is printing, but I still cant see them
Make sure the height is above the highest point of the terrain, and that the range from that height can hit the lowest point in the terrain. Then make sure that the area (negative / positive positions) is mapped to the dimensions of your terrain. If your terrain is centered in the world, you will have to use the negative dimensions as well (half extents into the negative, and half extents into the positive).
If it is actually calling .Play and the Fireflies are spawned in reasonable locations (which you can see by just looking in the hierarchy), then I would look at your particle system and make sure it looks as expected
Placed a Fireflies prefab in the scene and it looks how it did before. How exactly do I get the lowest and highest point of the terrain? Sorry 😅 I know where to get the width and length at least
Got it
Thank you
That's not what the error says though
It says that the type exists in both namespaces, see the Compiler Error CS0433
So this video explains my problem quite well, but in case anyone doesn't want to listen to my voice lol
I'm trying to implement a minimap into my mobile game. The mini map is basically an orthographic camera that feeds its render texture into a raw image UI in a canvas group so the player can see the map.
My problem is the interaction with the map. The player needs to be able to double click on the map and set a destination where they clicked, but I just don't know how to calculate that because of all the factors, the world position of the players click, the world position translated to the map position, the size of the orthographic camera (if that's even a factor) etc.
Idk what to do XD Please help
Here's my current code.
https://pastebin.com/WPC6FUXZ
I attempted to just get the localPosition of the players click relative to the UI image, which the size and scale I know, and translate it to the map position +- the cameras position, since the cameras position is the center of the UI image.
Didn't work, heh...
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.
So I am working on a thing to make it easier to add feedback/juice. The idea being that there are pre-made effects (Move object, shake camera, play particle system, etc.), that you can then easily play.
But I am having a hard time deciding on a good API that feels easy to use, and easy to find/select the effect you want.
// A: Not discoverable, feels a little 'raw' to me?
new PositionEffect(0.25f)
.WithEase(Ease.OutElastic)
.ToRelative(new Vector3(0, 1, 0))
.Play(transform);
// B: Very discoverable, feels a little verbose?
EffectEngine.Create()
.PositionEffect(0.25f)
.WithEase(Ease.OutElastic)
.ToRelative(new Vector3(0, 1, 0))
.Play(transform);
// C: Sort of discoverable.
EffectEngine.Create<PositionEffect>(0.25f)
.WithEase(Ease.OutElastic)
.ToRelative(new Vector3(0, 1, 0))
.Play(transform);
// D: Something else?
Anyone got any thoughts or suggestions?
if anyone is just busy or don't know
Personally, I find C the best, but why don't you combine all those extension methods into a single one?
Or make them properties and use the Property initialization expression
I could, but that tends to be harder to read since you don't have the names, and also can get long. So you would put it on multiple lines, and possible put the parameter names there. So ends up being pretty much the same.
where is your code posted
Yes, I would do it this way, and perhaps consider adding the arguments if the list is long enough
EffectEngine.Create<PositionEffect>
(position: 0.25f, ease: Ease.OutElastic, position: new(0, 1, 0), play: transform);
remember that you can use named arguments for long methods, assuming you use defaults. Also remember that defaults can only be primitive types
here
long argument lists are pretty shitty, for example when you want to compose effects later or when you refector or when the API changes.
much better with the named arguments now*
I was thinking of that as a option. But at least to me, that can feel rather verbose, and doesn't let you do stuff like .ToRelative(pos) , as you would need to do like .Space = Space.Relative and .To = pos.
Well, yeah, but 4 arguments is still not too much. I usually find my methods easy to read without the named arguments
Yeah that was my point, you can add the argument names, but then it feels to me like the same amount of work, but harder to type out. At least in my experience when dealing with a lot of default arguments, it is hard to see what all the arguments are and the IDE doesn't like putting the argument name there. Maybe others have a different experience?
im not gonna lie, that code is awful and hard to read. where does the players anim get reset after they respawn?
yeah, 4 is easy, although I assume he wants to make some massive "effect factory" kind of thing with many possible options. Possible extension points as well?
I was thinking of something like
new Effect {
Space = Space.Relative,
Pos = pos,
Easing = Ease.OutElastic
}
I think in the checkpoint script, it works for player 2, but not player 1 and before that it worked for both of them
I think
😅
Yeah, this might actually look more readable for me
EffectEngine.Create<PositionEffect>(new()
{
Space = Space.Relative,
Pos = pos,
Easing = Ease.OutElastic
});
Hey guys!! I am having some trouble with some basic translation and am not sure what am I missing out... so all I want is the projectile to face the direction they are moving in... it basically spawns in the direction of the mouse click and should move in that direction... I was able to rotate the projectile in that direction but the translation doesnt work... am not sure what am I missing out:
Projectile Movement script
IEnumerator MoveTowardsTarget(Vector2 target)
{
float time = 0f;
target.Normalize();
while (time < mLifetime)
{
transform.Translate(target * Time.deltaTime * mSpeed);
time += Time.deltaTime;
yield return null;
}
Destroy(this.gameObject);
}
Spawning the Projectile
private void Update()
{
Vector2 mousePos = Input.mousePosition;
Vector2 mPos = Camera.main.ScreenToWorldPoint(mousePos);
if (Input.GetMouseButtonUp(0))
{
p = Instantiate(BigProjectilePrefab, transform.position, Quaternion.identity);
dir = mPos - (Vector2)p.transform.position;
//angle = Vector2.Angle(p.transform.right, dir);
// Quaternion rot = Quaternion.AngleAxis(angle, Vector3.forward);
// p.transform.rotation = rot;
//p.Init(p.transform.right);
angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Quaternion rot = Quaternion.Euler(0, 0, angle);
p.transform.rotation = rot;
p.Init(dir);
}
if (p)
{
txtLog.text = "dir: " + dir + " angle: " + angle;
}
}
Yeah basically, it would be something like EffectEngine.Create().PositionEffect(..) with PositionEffect being an extension method, so it would be easy to add more custom ones and such.
Plus it gets complex quick, once you start adding looping, and to and from positions and relative space for each.
iirc IDE formatting of parameter names with defaults can be hard to read, I don't recall IDEs formatting params in new rows, rather they are all smushed together in one wrapping line
Please, consider using code sites for big code blocks
yeah, it was long time agosince i looked ad these scripts, idk if it's checkpoint or hitpoints. because both of the players worked alright before
Yeah, that is my experience as well, and why I don't think using a single method works well.
but at the same thing comes with the Parameter initialization method, they also wrap
Yeah, maybe something like that could work. But not sure if it is more readable or easier to type then doing a more fluent style like A
i feel like im gonna go insane trying to understand that code and debug it
It probably looks the same with named arguments
please please please clean it up
I'm sorry
how familiar are you with coding in general?
hmmm.... idk, #archived-code-general message it works for player 2 but not player 1, and after those videos i fixed the death animations, but the respawn for player 1
there goes nothing:
https://paste.ofcode.org/upwnNSjCzEXCk8twjkKATg
although... I think you might be bikeshedding a bit too much at this point, at some point it might be not worth trading some amount of* DX for example for performance etc.
but the respawn for player 1
???
so what is you current issue?
Yeah, I probably am spending too much time on it haha 😅
1st rule of Tooster's procrastination checklist:
- Is what you are currently doing a detail?
xd
Haha, good checklist
there are like 21 points for my own sanity on that list xD
like when player 2 dies, they both respawn and it works alright for player 2, and the health ui goes back to full, but for player 1 if that dies and respawn, she's just cimpletely stuck, unmoving and the healthui doesn't go back to full health
do you get any console errors?
nope
please add debug statements to each func and then decide what isnt working from there
its impossible for me to discern that as is with how bad this code is setup
My unity editor crashed and when i reopened it i got a bunch of these errors that havnt been there before
ok
how's this?
hi everyone are you using any code for your game's compatibility with different devices (for screen edge gaps , object size , object locations , objects outside the screen etc.)
its not about canva
its about other objects that not in the canva
now add a debug after where "resethitpoints()" gets called
I want to make a trail renderer go around the edge of a ui element. What would be the best way to go about this?
you have two of the same debug statement but it is only called once (the one in the hitpoint script is called but not in the checkpoint script)
yeah, which is pretty weird for me because both of the players have literally the same thing in the script
wdym "the same thing"?
in the checkpoint script https://gdl.space/bulividehi.cs in the player bool
and both of the players have like the same thing, literally
i mean... you already know what the problem is. I would say to clean up your code and debug some more
what do you mean by clean up my code?
here, i did it for you https://gdl.space/ojakoruyew.cs
this way the script is a lot more neat and easy to understand
now use this version of your script and debug it if it doesnt work
ok, imma try it
there seems to be an error
Error says Check Point 46
ah sorry there should be a space in "PlayerManager"
it should be "Player Manager"
ok
also this is something very basic you shouldve seen and have been able to compare on your own
ok
ok what? now debug your scripts and see what doesnt run
ok
hang on, let me try out player 2 first.
now it seems the same thing happening to player 2 ever since the coding change
so add debugs and see what isnt running
Apologies for interrupting. :)))
How can I make a rigidbody based character controller handle steps properly and walk up and down stairs smoothly?
You may want to consider making it a slope in terms of the collider
And it only looks like stairs
I thought about that but it feels like cheating.
It's pretty common
The kinematic character controller seems way to complicated IMO.
Is there a way to add padding when using stretch?
why is respawn being called at the beggining?
Hey guys! I'm making a game with an Earthbound style encounter system, there are enemies in the overworld, and if you come into contact with any of these enemies a fight starts. However in Earthbound if you come into contact you might encounter more than one enemy, and not necessarily the same type of enemy
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public enum Biome
{
spring,
beach,
forest,
mountain
}
public class BattleTrigger : MonoBehaviour
{
public EnemyObject enemy;
public Biome biome;
void OnTriggerEnter2D()
{
BattleRelayInfo.instance.Relay(enemy, biome);
SceneManager.LoadScene("BattleScene");
}
}
I currently have this script rn and was wondering how I could change it to achieve what I want, does anyone know how?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BattleRelayInfo : MonoBehaviour
{
public static BattleRelayInfo instance;
public EnemyObject enemy;
public Biome biome;
void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(this.gameObject);
}
else
{
Destroy(this.gameObject);
return;
}
instance = this;
DontDestroyOnLoad(this.gameObject);
}
public void Relay(EnemyObject enemy, Biome biome)
{
this.enemy = enemy;
this.biome = biome;
}
}
this script is also involved
Hi guys, is it alright to ask around here about my problem in navmesh?
hey man thanks
Also i want the mupltiple enemies to only have a certain chance to spawn not all the time
can anyone help me with this? basically i made Controls and for some reason it keeps giving this error
private void LateUpdate()
{
look.ProcessLook(onFoot.Look.ReadValue<Vector2>());
}```
heres the script
this is script from line 28 to 30
read the error again, its very self explanatory
there is no "look" method
there is though
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class InputManager : MonoBehaviour
{
private PlayerInput playerInput;
public PlayerInput.OnFootActions onFoot;
private PlayerMotor motor;
private PlayerLook look;
void Awake()
{
playerInput = new PlayerInput();
onFoot = playerInput.OnFoot;
motor = GetComponent<PlayerMotor>();
look = GetComponent<PlayerLook>();
}
void FixedUpdate()
{
motor.ProcessMove(onFoot.Movement.ReadValue<Vector2>());
}
private void LateUpdate()
{
look.ProcessLook(onFoot.Look.ReadValue<Vector2>());
}
private void OnEnable()
{
onFoot.Enable();
onFoot.Jump.performed += ctx => motor.Jump();
}
private void OnDisable()
{
onFoot.Disable();
}
}
here's the full script
I think you need to look at the OnFootActions script
"PlayerInput.OnFootActions does not contain a definition..."
God I hate this tutorial for its absolutely asinine naming of things
Anyway your problem is in your input action asset
You probably didn't name things the same way as the tutorial
i see
I didn't really do the same thing as tutorial because it wasn't working right as it was in the video so we edited a bit with my friend
the jump script wasn't working and we needed to do something way different to make it work
If you're following a tutorial you need to follow it unless you understand the basic principles around what it's doing
You have a simple naming problem here
If you didn't name the action Look it won't be called that in the code
can i be because of this action not having a name?
I think you should watch and follow the tutorial exactly and then freestyle when you get the hang of it my guy. That way you won't get lost in the sauce
The code is expecting you made an action called "Look" like in the tutorial
Renamed it into "Look" what should i do now?
Yes it worked, thank you so much.
can someone help me with this?
oh you lookin for a way to retain enemy and biome when you change scenes? or what's the exact problem
no it's not that, I already have that down, it's that I want there to possibly be multiple enemies passed along with each trigger
ohhh ok gotcha because the code you made can only send one
idk, but maybe because since the player spawns from the checkpoint
I mean you could just pass a List<EnemyObject > instead of just one EnemyObject... I think 
so move you debug statements around because that provides 0 info as is
The thing is I only sometimes want multiple enemies, for example there might be a 100 percent chance of one enemy, a 20 percent chance of two, and 5 percent chance of three
then you may want to look at the params keyword which allows a variable number of parameters
How would I use that in my context?
public void Relay(Biome biome, params EnemyObject[] enemies)
...
BattleRelayInfo.instance.Relay(biome, enemy1, enemy2 etc);
how would I implement the spawnChance and such?
no idea, outside the scope of your question
because I could just use a list to do this as well but that's not necessarily what I want
What I was saying is that I wanted to have a list with two values kind of, an EnemyObject, and a spawnChance
ohhh
i tried a Dictionary but you can't see those in the inspector i don't think
then use a tuple
Ok, I'll try that
You can't view tuples in the inspector and I would have to manually assign these in the Inspector, there's no other way, so how would I do that?
Make a struct that holds those objects
sorry, I'm not familiar with structs
I think its just a little confusing. do you want to do something like (Logic Wise)
100%
BattleRelayInfo.instance.Relay(biome, enemy1);
20%
BattleRelayInfo.instance.Relay(biome, enemy1, enemy2);
5%
BattleRelayInfo.instance.Relay(biome, enemy1, enemy2, enemy3);
ohh sorry my bad you also want it to be editable in Inspector
my guess is you want to be able to play around with the values in inspector. Like being able to put 10% as 4 enemies or 25% chance of 8 enemies but all in inspector right?
yeah that's basically what I want
also this one?
Sorry I think i read it wrong, I want there to be a list of enemies, with each enemy having a certain probability of spawning, and I want it to be editable in the inspector
I'm not sure if that's possible or not
there the respawn thing
wait I think I'm getting it lemme cook something up for ya
ok, ty
I think the chance thing can be a simple array
[Serializable]
public struct EnemySpawn
{
public EnemyObject enemyObject;
public int chance;
}
here you go my guy
should be something like this
my bad dont forget:
public List<EnemySpawn> EnemySpawnList;
I tried using a struct and it didnt appear in the inspector
did i do something wrong
put the [Serializable] ontop
dont worry @hexed fjord took us a while to understand the requirements 
do note tho that can only spawn ONE enemy per chance rolled. so if ever you want a more flexible amount of enemies being spawned per roll
just use
public List<EnemyObject> enemyObject;
isntead of
public EnemyObject enemyObject;
Im late but this is what i was making
public GameObject[] enemies;
public int[] spawnChance;
//You set the probabilities from biggest to lowest, but adding all before it
//For example: 80 (80%), 90 (10%), 95 (5%), 100 (5%)
void SpawnFunction(){
int rand = Random.Range(1, 101); //Gives a value from 1-100
for(int i=0; i<spawnChance.Lenght; i++){
if(rand <= spawnChance){
//Spawn this enemy and all before it in the array
for(int k=0; k<=i; k++){
//Spawn enemies[k];
}
}
}
}
now i just need to know how to use probability to do this
just do something scuff like
Random.Range
public void SpawnEnemy()
{
for(int i = 0; i < enemies.Count; i ++)
{
GameObject log = Instantiate(enemies[i].enemyObject.enemyPrefab, enemySpawnPoint.position, Quaternion.identity);
Log logScript = log.GetComponent<Log>();
logScript.target = player.transform;
logScript.moveSpeed = 2;
logScript.attackRadius = 1;
logScript.anim = log.GetComponent<Animator>();
logScript.myRigidbody = log.GetComponent<Rigidbody2D>();
}
}
i just want to do this but with the prob stuff
also the script is scuffed because it only allows one enemy type
but ill ignore that for now
you can change
public List<EnemyObject> enemyObject;
to
public List<GameObject> enemyObject;
so you can put different prefabs instead
or
public List<MonoBehaviour> enemyObject;
for scripts
this ones nice too, can even do a 2D Array
all enemies should derive from an Enemy script, it's just that all the variables are different, for the ones that are different i think I should just use a scriptable object
ah I see yeah this time it can go alotta ways. Have fun experimenting haha
ty for the help, it's done a lot
I guess it must be something with where i put the debug or something. and the fact it didn't debug the backfull health thing
Guys do you know how to optimize shadowcasters2d? I have a lot of them in different areas and I was thinking about making circle cast every frame
and turning on only ones in the visible range of player, how can I do that?
Are you running into a performance problem with them?
no but it takes more then half of frame time
or is unity already doing that?
How come two rigidbodies on layers that should not collide still enter in collision, is that the expected result?
Also tried manually specifying it with Physics.IgnoreLayerCollision
nvm
not expected no.
Why do both Debugs fire here when I start the game in the Editor?
probably because you have WebGL selected as the build target. If you want platform dependent code try Application.platform
does it something to do with if (player2D != null) ?
Player2D is a script that is for the players
as long I'll wait till the respond
is there a fix or solution to "waiting for unity code to finish executing" ?? for some reason that appears and unity never enter to playmode
sounds like you have an infinite loop in your code
Why am I getting Assertion failed on expression: 'CurrentThreadIsMainThread()' from JsonUtility.ToJson if ToJsonInternal has the ThreadSafe attribute? Unless that attribute actually means it needs to be on the main thread?
Uhhhhh, Has anyone got any ideas?
what is the error say, and what type is laptime
make sure you're passing a string
try laptime.ToString().
This confused me when first starting out coding and w/ unity. Unity's Debug.Log takes an object so you can pass anything into it and it converts it to its string representation. I got used to that, and when I first encountered a situation where I needed to pass a number as a string I was confused.
(realized I put the wrong screenshot)
thats worked, but it doesnt write teh contents of teh variable
what's it write?
Besttime
what type is Besttime?
You set bestTime to lapTime right before writing to the file, so it's normal that they're equal
does it literally write "Besttime" or does it write the value of besttime? The way you worded it made it sound like it's writing "Besttime" to me.
So this video explains my problem quite well, but in case anyone doesn't want to listen to my voice lol
I'm trying to implement a minimap into my mobile game. The mini map is basically an orthographic camera that feeds its render texture into a raw image UI in a canvas group so the player can see the map.
My problem is the interaction with the map. The player needs to be able to double click on the map and set a destination where they clicked, but I just don't know how to calculate that because of all the factors, the world position of the players click, the world position translated to the map position, the size of the orthographic camera (if that's even a factor) etc.
Idk what to do XD Please help
Here's my current code.
https://pastebin.com/WPC6FUXZ
I attempted to just get the localPosition of the players click relative to the UI image, which the size and scale I know, and translate it to the map position +- the cameras position, since the cameras position is the center of the UI image.
Didn't work, heh...
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.
it writes "best time" nopt teh value
is it an enum?
Show your updated code, a float converted to a string does not return the variable name it was in
This is it.
BestTime looks like another variable you haven't told us about yet
ooooo
(that's why you don't name them so similarly)
I know, but its too late to change it now,
Here you go
It's never too late, VS provides tools to rename things and reflect the changes everywhere the name is used
still doesn't show BestTime
it does 3rd on up
oh my bad I misread it
yea, so BestTime is a UI element, so it looks like it's printing the text it contains
AI code isn't it..
nope
its for my computer science coursework, one of the things on teh mark scheme says to comment my code
yes
but it isnt :/
ohh ok. Overcommenting is wild
They should teach you good code generally comments itself lol
I've had professors insist on things like this too...
then the name of the game object
Yeah, but A, my teacher cant teach people to code, she cant code herself and B i mayswell comment everything and potttentialy get marks lol
wdym?
it's printing the name of the game object
so i should put besttime?
can you perhaps get the texel coordinate where you clicked, normalize that, then use ViewportPointToRay on the camera that renders to the render texture to raycast?
For example (pseudocode, I wrote this in discord, I hope you get the idea of it), something like this:
RectTransform r = mapImage.GetComponent<RectTransform>()
if(RectTransformutility.ScreenpointToLocalPointInRectangle(r, Input.mousePosition, Camera.main, out Vector2 point)) {
x = ((point.x - r.x) * mapImage.width)/r.width;
y = ((point.y - r.y) * mapImage.height)/r.height;
Ray ray = mapCamera.ViewportPointToRay(new Vector3(x, y, mapCamera.nearClippingPlane);
// do your raycast stuff from here
}
This still doesnt work, i tried laptime and i also put it above where i re-assign teh variable
(Old screenshot by accident so ig 'trust me bro')
Hey guys, I have a game manager script that is persistent. How can I make sure the references between levels (unity events) are not lost when the level switches?
What do you mean by making sure they're not lost? Do both persist between scenes? If not, perhaps resubscribe in the next scene on start
So let's say my GameManager handles a method called LoadScene(string sceneName)
I use unity events so when the player from the main menu clicks "Play Game", it fires LoadScene("Level1")
Okay so it does exactly that woohoo. But then it gets to Level1 and the player wants to return to the menu. GameManager, which is persistent, cannot be referenced on the "Back to menu" button because it didn't exist already in that level, only MainMenu.
I can reference the level objects in static fields. But the issue is they are not serialized and that's really what I am aiming for.
The reason a method like GameManager.LoadScene(string sceneName) exists is again, due to serialisation
well that certainly doesn't look like a valid path
also the Assets folder will not exist inside of a build, consider writing to Application.persistentDataPath instead
Okay well I guess I can extend my question to: How do I handle levels in a game with many scenes?
If you read my question it gives you an idea of how I treat it now, any better way?
why not save it in Application.persistentDataPath
no idea where that is lol
let me find it
But that didnt work
it did not save anything to teh txt
because you somehow made it even worse
Can someone just tell me what to put 😭
string path = Path.Combine(Application.persistentDataPath, filename.txt)
I am actually aware a level manager exists in Unity, it just isn't serialised due to Scene being a custom type
there is not a persistent data path
that is the persistentDataPath
that folder you are currently viewing is what Application.persistentDataPath returns the path for
did you know that it generally helps to ask questions about what you are confused about instead of assuming someone will read your mind to know what it is that needs explaining?
Windows Editor and Standalone Player: Application.persistentDataPath usually points to %userprofile%\AppData\LocalLow\<companyname>\<productname>. It is resolved by SHGetKnownFolderPath with FOLDERID_LocalAppDataLow, or SHGetFolderPathW with CSIDL_LOCAL_APPDATA if the former is not available. From the docs navarone said
this is Windows Editor and Standalone Player (considering this is in editor)
The whole thing can be avoided by just reading the docs
so then what are you confused about
show your current code and what you've done to ensure that the code is actually running
Here is my code, i have .debug in multiple places so i know it is running as i recieve teh messages.
!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.
also wtf why are you hardcoding the path like that. navarone literally gave you the code to create the path using Application.persistentDataPath
wild
use link sites
I THINK I get it...?
But I can't get .x and .y from r because r is a RectTransform and not a Vector.
Would I just do.... r.transform.position.x...?
yeah - ill use pastebin
r.position would be equivalent
RectTransform is a child of Transform
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.
if you're going to use pastebin, at least have the courtesy of selecting the language so there's syntax highlighting
this site kinda sucks please use the ones from the bot
oh my bad, r should be this I think:
r = mapImage.GetComponent<RectTransform>().rect
and again, what are you actually doing to ensure that the line of code that writes to the file actually runs. you didn't bother putting any debugs in here, and with your complete lack of understanding of how to get a real path, i assume you also don't know how to use breakpoints in your code editor
basically you're trying to create a viewport point out of the location you clicked on of the image. A viewport point is 0-1, so normalizing the point you clicked on in the image to be 0-1 as well will give you a viewport point.
Oh, you want the rect :p
I know it runs, because i can visually see the changes on screen from the UI ext elements
no idea why you hardcoded that path
do not make assumptions about what is actually happening in your code. you need to actually verify that the code is running
also there is nothing at all that would be updating when that line runs
when you assume, you make an "ass" out of "u" and "me" (:
assumptions lead to hours of wasted time
"measure twice, cut once"
im pretty sure, right? Im not testing this code. But the idea behind what I'm saying is sound.
and do you know what that means?
none of that code is being read
Woof that path
it's not that the code isn't being read, because nothing here is doing any reading. it's that either you have an error in your console that is being ignored or that code is not actually running
That's just the persistent data path isn't it
yep. we told them to use Application.persistentDataPath and navarone even gave a line of code that would create the path using that.
this was the result of that advice (but hey, at least they aren't trying to write to C:\Assets now)
the code is not running as there are no errors in the logs
screenshot the entire console window
Soooo... you do have errors that should be addressed.
But you cropped off part of the console
The important part on the top right
well you seem to have Non-convex mesh colliders with non-kinematic rigid bodies. Why are you even using mesh colliders 0.o
What number does it say for errors
also not scrolled all the way down
mapImage is the display of the map, correct? Like the raw Image that is being fed the miniMap camera render image. Or is mapImage my 10,000x10,000 map?
you should be able to use the Image component I believe. Like the thing that renders it onto the screen.
the rest are just debug.logs
I know the box collider is not an issue as its a trigger and everything else it is assigned to do works and activates when it is touched
honestly there is just so much wrong with the logic here. it is going to be a real pain in the ass to figure out what is wrong with it.
one of the worst things you are doing is relying on gameobject names for your logic
so "written" isn't there?
including the stuff that is in the same script
yeah agreed with boxfriend, soo much can go wrong there
Seems like the piece of code that writes to the file is nested in another block { }, maybe it's an if statement whose condition never passes...
is LapTimeCheckpoint even the character /vehicle ?
Yooooo ok
I moved this out of the { } and i got an error with the path 💀
saying it cant find the path
now use the proper path then
#archived-code-general message
they said it's not AI generated earlier but looking at it all im starting to feel that its AI generated with the way the comments are. I understand the over-commenting for the fields (as I've had professors require that in the past), but...
//Sets bool to true
checkpoint2 = true;
but also how they understand 0 of their own code
Well, don't just move it out, debug why the execution didn't enter the statement
im trying to make a mobile game and im just confused on one thing. Scale. When im in the editor with my game and i play the borders ive made with a game object are fine but when i build to my test phone the borders arnt there and they are off screen. I dont understand how to get game objects to transform ocrding to the device res
also I've tried AI-generated code in the past (not copilot yet, gonna try that this summer), and it does things like other.gameObject.name == "checkpoint2"
I know, but surely i should give it a path that works and see if it detects it?
Yes, just make sure you do both in the end
I have spent like 5 hours writing this....
Yeah idk anymore XD
https://pastebin.com/xsyuud3F
The mapImage is the NewMap which is 1000x1350, the image the player interacts with to move and zoom the camera.
And it's coordinates are way off when the player double clicks
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.
That's the neat part! (you don't)
ah so then whats like the "best" res to build my game with
that's why mobile games are hard. You can use the simulator option to see how it looks on different devices. You can probably change your Camera's FOV or projection matrix if needed.
welp i got it working
probably something wrong with my code (i wrote it in here), but what's set destination marker do?
Anyone wanna share the gravity and initialJumpVelocity values that work for you?
Just curious
public void SetDestinationMarker(Vector2 Pos)
{
destinationPositionBool = 1;
destinationPosition = Pos;
destinationMarker.gameObject.SetActive(true);
// Set the destination marker's position
destinationMarker.transform.localPosition = destinationPosition;
// Start moving the ship towards the destination
isMoving = true;
// Update travel time text
UpdateTravelTime();
}
This is what it does. It basically sets my DestinationMarkers localPosition as the inputted position after the calculation and then activates it.
The destinationMarker is a child of my minimaps worldSpace canvas. So it its position is 700X 800Y, that is it's possible compared to the minimap
well you're missing the whole using ViewportPointToRay part to raycast that and get the position that it hits.
"Pos" should be some value in the range of: (0-1, 0-1) If we did everything correctly
Ohhhhhhhh
I think your question needs more context, what is it your trying to do or solve? What are those values your referring to? And what system are they meant to be a part of? There are many ways to build a system, so just simply copying someone elses values may not solve whatever problem your currently having with your system, if your system is not coded and setup the exact same way as someone providing those values
aah sorry, I just implemented a jump functionality, but it feels a bit snappy. I have jumpVelocity as 40 and gravity as -1, and the jump is done in under a second
I'd like for it to last, so that I can see the parabola and it feels a bit smooth if that makes sense
You should really share your code. Gravity as -1 in what context, how is jumpVelocity used? 40 also seems absurdly high
i suspect some rb and unneccesary Time.deltaTime usage
{
Vector3 newMovementDirection = new Vector3(_psm.playerInputManager.inputMovement.x, 0, _psm.playerInputManager.inputMovement.y);
if(newMovementDirection.magnitude > 0){
_psm.movementDirection = newMovementDirection;
}
_psm.speed += newMovementDirection.magnitude > 0 ? _psm.acceleration : _psm.decceleration;
clampSpeed();
_psm.playerAnimationManager.updateParameter(0, _psm.speed);
handleGravity();
Vector3 finalMovement = _psm.movementDirection * _psm.speed + new Vector3(0, _psm.ySpeed, 0);
Debug.Log(finalMovement);
_psm.playerCharacterController.Move( finalMovement * Time.deltaTime);
}
private void handleGravity(){
_psm.ySpeed += _psm.gravity;
}```
here _psm.speed refers to the XZ plane speed
which is also the same when I am on the ground
first thing i notice is that your handle gravity logic doesnt use deltaTime, which is probably why your jump is done so fast
I see, so I have to use deltaTime to update both the velocity and position?
you want the gravity to increase at X units per second, not per frame
assuming logic() is called every frame
yep, gotcha
makes sense, that v = u+a*t
Thanks
Hi I'm working on a controller where movment is based on the gravity direction as gravity direction will change dynamically:
To further explain, my gravity will always be the players y axis as far as movement goes, how do I move in the perpendicular x and z axes if y is changing
You can look up the concept of the cross product, which is how you calculate perpendicular vectors.
Fortunately, Unity has a built in Vector3.Cross utility function
I've been looking into using the Cross product, just been messing up which directions to use to get my desired result
maybe between gravity direction and camera.up?
I'll try it
It would be the gravity direction and the forward direction of the player
I'm building a sort of Gravity Rush style game so the player's forward may not be a reliable source
You have its movement direction though, which you can use as the forward at least. Make sure you're normalizing your vectors as well before you cross them.
thanks
Ty

hello guys, I'm trying to create a crafting system in my game. Basically I interact with an object and then a UI appears with for example 3 slots 2 for the inputs one for the output but this is the first time I make something like that and I can't really wrap my head around it.
I already have a functional inventory system, 4 slots that holds scriptable objects called item
If you already have a functional inventory system, it sounds like your half way there, which part specifically are you struggling with? Are you trying to toggle a UI/Canvas? Detect a "interactable object"? Something else? You also mentioned your crafting system is meant to have 3 slots, is this static or dynamic slots? As in, will some items may have more or less than 3?
Some crafting machines have more than 3 slots, as for what im struggling with, literally just cant wrap my head around how I can create that system. I have tried simplifying it to myself with a pseudocode and stuff like that but still
there must be a upper bound of slot number (otherwise imagine you can have a 2147483648 slots)
no idea what you are asking, if you are asking how to UI interaction then i cant answer you....
but if you are asking how to check the input pattern/give suggestions based on input then tree can solve it
I guess I will try to do something and come back with a better question because each time I do something I am just like nah and I delete it all
split it up by steps, with 4 slots or even a short list of craftable items you could do pretty much anything to get a list of craftable ingredients based on an inventory. If you plan on having a large list of craftable stuff, then id worry about efficiency. This still doesnt affect other code, its still outputting the same thing
Then worry about the UI which at the end of the day, hooks up a button to a method. That method will take items and spit out the item
alright thanks
I haven't done unity for a hot while and I feel like I might just be missing something...
I have a prefab with a rigidbody2d, and i'm dynamically instantiating it and setting a velocity to it.
The prefab gets instantiated, but the velocity is always 0. I've logged out the vector i'm using and it's not 0. I've tried setting the velocity after the instantiation and in a Start on the prefab.
Am i just forgetting something?
the code is just a rigidbody.velocity = new Vector2(...);
you would have to show some more code and also show / explain your scene
Might want to share more of the code, especially the part where you instantiate.
I'll have to be back in a bit then
My guess without code is that either the rigidbody is kinematic or you are setting the velocity of the prefab
Oh, you said the velocity setting is in start. So it wouldn't be the second guess
the rigidbody is dynamic, i recall checking that
the instantiation is here, i used to have the velocity setting here and it didn't work either```cs
private IEnumerator<YieldInstruction> SpawnProjectile() {
while (true) {
yield return new WaitForSeconds(projectileSpawnInterval / 2);
GameObject projectile = Instantiate(projectilePrefab);
projectile.transform.position = transform.position;
yield return new WaitForSeconds(projectileSpawnInterval / 2);
}
}
public void Start() {
// public void Update() {
Vector2 position = transform.position;
Vector2 target = player.transform.position;
float angle = Mathf.Atan2(position.y - target.y, position.x - target.x);
Debug.Log(angle);
Debug.Log(new Vector2(
Mathf.Cos(angle),
Mathf.Sin(angle)
) * speed);
// WHY?????
rigidbody.velocity = new Vector2(
Mathf.Cos(angle),
Mathf.Sin(angle)
) * speed;
StartCoroutine(Expire());
}
```this is the entire start method on the prefab, and the logs are hit and show non-zero values
IEnumerator<YieldInstruction> this is not how you properly declare a coroutine
Just use IEnumerator
You immediately set the transform's position, which may override its velocity
you should use the instantiate overload that takes a position (and rotation)
why is this, btw? i'm from a java background so using a generic over a "raw" type feels more correct to me
Coroutines in Unity are old and integrated with unmanaged code, it's just how it's done
good news I made the crafting system and it was easier than I thought I just like to overcomplicate things, im only missing the UI 👍
is there any drawback to using the generic though?
If it works, I can't imagine there are any. It's not the way it's written in any docs or code I've seen though, so I wouldn't be surprised to find it didn't
it's been working fine for me
Then I've learnt a new useless fact 😄
i'll probably just use this then to satisfy my java brain lol
Hey, If this is not code related why are you posting in a code channel?
i dont know where i should post it
but tell me ill move it
working now 🎉
thanks for the insight
Does anyone know why the result of InverseTransformVector() method may not match the manual calculation using rotation and position of that transform?
var altLocalVector = math.mul( math.inverse( transform.rotation ), vector - transform.position );```
Because InverseTransformVector does not consider the position of the transform, only the rotation and scale. What your manual calculation is doing is closer to InverseTransformPoint, except yours doesn't take scale into account.
Thank you very much, I had no idea that I shouldn't use position.
Is atan means arc tan ?
hey everyone, im trying to make an AI enemy that shoots in bursts.
The issue im having is that canShoot is always true, and while the cooldown isnt happening the enemy shoots a bullet every frame instead of using the Invoke() to reset it.
if (canSeePlayer)
{
timeSincePlayerSeen += Time.fixedDeltaTime;
eyePos.forward = lastPositionPlayerSeen - transform.position;
if (timeSincePlayerSeen == 0)
{
CooldownShot();
ResetShot();
}
//if (timeSincePlayerSeen < reactionTime) canShoot = false;
if (canShoot && roundsLeftInBurst > 0)
{
Instantiate(bulletPrefab, eyePos.position, eyePos.rotation);
canShoot = false;
roundsLeftInBurst--;
//Invoke(nameof(ResetShot), 50/650);
Invoke(nameof(ResetShot), 0.25f);
}
if(roundsLeftInBurst <= 0)
{
canShoot = false;
Invoke(nameof(CooldownShot), cooldown);
Invoke(nameof(ResetShot), cooldown);
}
}```
this is happening inside FixedUpdate but ive tried Update as well
#archived-code-general message does this have something to do with the player2D this?
if (timeSincePlayerSeen == 0)
never test floats for equality
When im working with a canvas why sometimes i can make bigger stuff from it only by dragging and other times i just cant do it, just if i was using a normal gameobject?
would agree, but i have an else timeSincePlayerSeen = 0; if the player is not seen
so it will be zero
though i should put that before i += it....
Hey I want to instantiate various objects randomly. How can I check if an object is already placed at the position so that I don't spawn one if there is?
and that isnt the issue here
you see this is the problem where you edit what you post and we only see snippets YOU think are important
cant fit it into 1 message
that is why we have !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.
use a paste site
cannot see anything obviously wrong with the code. you'll need to throw some Debugs in there to follow the paths taken
Can you show an example of when you cannot do this? And the object your trying to affect?
i dont know what youre asking but i cant really hold your hand through this and help you since youre the only one with access to the project
this looks like a huge waste of time if you dont know basic coding principles
so i am setting up footsteps with a script and i checked the script and idk whats causing the footsteps to bug out. It plays like on or two and then it plays like a very very silent click if i can even call it a click. A very and i mean very silent sound instead of a footstep. Idk how to rightly configure audio but i have tried setting its priority to both the highest and the lowest. ```
[Header("References")]
public AudioClip[] footsteps;
[Header("Attributes")]
public float stepInterval = 0.6f;
[Range(0, 1f)] public float stepWidth = 0.3f;
private AudioSource audioSource;
private bool isWalking;
private bool waitingForStep;
private bool rightStep = false;
void Start()
{
audioSource = gameObject.GetComponent<AudioSource>();
}
void Update()
{
isWalking = Input.GetButton("Vertical") || Input.GetButton("Horizontal");
if (isWalking && !waitingForStep)
{
StartCoroutine(WaitForStep());
}
else if (!isWalking)
{
waitingForStep = false;
StopAllCoroutines();
}
}
void TakeStep()
{
int newStepIndex = Random.Range(0, footsteps.Length);
if (rightStep)
{
audioSource.panStereo = stepWidth;
}
else
{
audioSource.panStereo = -stepWidth;
}
audioSource.clip = footsteps[newStepIndex];
audioSource.Play();
rightStep = !rightStep;
}
IEnumerator WaitForStep()
{
while (isWalking)
{
TakeStep();
waitingForStep = true;
yield return new WaitForSeconds(stepInterval);
waitingForStep = false;
}
}
}
already fixed it, thx anyway!
Sounds like your audio may be overlapping, which suggests you may be calling your functions more often than you think, try adding a Debug log to the start of your coroutine outside your while loop to make sure its only being called once, and inside your TakeStep function to make sure its being called the correct number of times as well, if those logs spam, you know your function is being called as often as the logs are
I meant at line 55 debug where the respawning player happen. like when I die and respawn, the healthui doesn't go back to full health and I can't move and is stuck in air. and this debug where i put triggers the respawn new player
so can you tell me why you think this is happening?
what exactly isnt working, from what you understand?
I don't know why it is not working, from what I'm saying, when I die by losing all of my health and lose a life, I'm supposed to respawn to where the checkpoint is and my health is suppsoed to be back to full health, but instead when I Die by losing all of my health and when I respawn from the checkpoint, my health isn't back to full health, and I am stuck in midair and I cannot move anywhere,
yes, but the reason this happens is because your function isnt being called
figure out why this is
I'm trying
your problem is that you dont understand basic coding concepts
you will never debug your code this way and you cannot expect others to do it for you
please learn c# and come back
I did that and it comes out corectly. I have setup the timing right with my animation. In the player i only have a "Audio Source". And i can see the stereo plan changes from 0.3 to -0.3 every half seccond or something like that.
I will never be able to know why and learn because no matter how much I learn, I always tend to forget things easily and that I'm so dumb...
i used to think the same thing when i first started out, but i promise you that even 1 week of genuine work will help you
you arent "stupid", youre just expecting things to magically work and for information to enter your brain without studying or practicing
here are my settings for the audio source
i would really recommend just watching c# tutorials on youtube and following along
just a few hours should be enough
I'm losing my mind here. The video explains my problem, but incase you don't want to watch it.
I'm trying to make a minimap for my game using an orthographic camera looking at a Canvas UI in world space that is 10,000x10,000. Which is my map. The orthographic cameras render images are fed into a raw image that the main camera can see. And I have it so the player can move the camera around/pan the camera as they drag on that raw image. And even scale the orthographic camera, by changing its size so they zoom in/out.
But now my problem is, calculating the position of the plays mouse click on the raw image, relative to the maps position. I don't know how to do that, at all. I need to somehow, using just the position of their mouse click relative to my raw image transform, translate that to my maps position so my other map script c an handle the logic of setting the players destination WHERE they clicked.
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.
I am currently the definition of insanity XD
I have been in a gaming coding school for 3 years, and yet. also I could barelly fidn anything ot a youtube tutorial viddeo about why the function isn't being called
no no no youve got it all wrong
you dont even know how to call functions at all
if you follow a beginner tutorial, you will know how to do that
these are like literally calling a function
so you know that but you dont know where your respawn function is called? 🤦♂️
i am done helping you until you seriously put some effort into trying to learn basic c# stuff
you are going to get nowhere like this
even if I do this, it wouldn't call the healthui
what do you mean "call the healthUI"?
youre finding it but not doing anything
this is where like you respawn (I did put the debug there) I mean like so it know like yhe health is supposed to be back to full health
int nextRoom = Random.Range(1, 5);
for (int tries = 0; tries < maxRoomTries &&
((nextRoom == 1 && Physics2D.Raycast(new Vector2(currentRoomPos.x, currentRoomPos.y), Vector2.up, distBtwRooms, roomLayerMask)) ||
(nextRoom == 2 && Physics2D.Raycast(new Vector2(currentRoomPos.x, currentRoomPos.y), Vector2.right, distBtwRooms, roomLayerMask)) ||
(nextRoom == 3 && Physics2D.Raycast(new Vector2(currentRoomPos.x, currentRoomPos.y), -Vector2.up, distBtwRooms, roomLayerMask)) ||
(nextRoom == 4 && Physics2D.Raycast(new Vector2(currentRoomPos.x, currentRoomPos.y), -Vector2.right, distBtwRooms, roomLayerMask)))
; tries++)
{
nextRoom = Random.Range(1, 5);
}
CreateRoom(nextRoom);
save my sould ive been trying to fix this for 2 days straight
im making a dungeon generator and checking if theres a room where im trying to spawn next room using raycast
you havent shown the full function, there is no way for me to know that
but for some reason it still spawns rooms ontop of rooms
I am your favorite son @ocean hollow
if this is grid based - why use raycasts?
i do not know who you are but i agree
what popped into my brain at the time honestly
i should prob make a list to where i spawn tiles right
Just save your rooms in the grid and check if there's something in the grid. Use a 2D array or a Dictionary<Vector2Int, Room>
i said function, like code
with this being said, i am done helping you
how does that work?
i have told you multiple times that you need to know the basics, which you obviously dont
https://gdl.space/fukemajoqa.cs I am showing the code here
...I just don't know why the function is not being called...
learn to code properly...
can I just get help from someone else?
depending on what data structure it'd be myArray[x, y] or myDictionary[theCoordinate] or myDictionary.Contains(coordinate)
you can try
YOu absolutely wouldn't use a List here @craggy oyster
it should be an array, a Dictionary, or a HashSet

a List will be much too slow
really
it's insane to look through the entire list when you know exactly which coordinate you want to check
it will be extremely slow
before this, when I hade my other coding script. everything worked perfecly fine that I can respawn and move that the full health back, but during some changes around in other scripts and during that.... this happen
i used lists for this sort of grid based maps many times before
that's... madness
can anyone else help me with this?
guess thats why i quit the projects for performance issues
It's kind of like if I said "Can you check if there's anyone living in Apartment 2B?" And you checked every apartment in the building rather than going straight to apartment 2B
yea i get it
You linked to you asking for help.
What is "this"?
i wasnt aware of the contains i think or i couldnt get it to work before i dont remember
thats why i used lists from that point
like whenever the player dies and respawn, they get stuck in midair, cannot move and the uihealth doesn't go back to full
Ok. Did you share code?
yes
here
!vscode
Well for one thing, you have if (!isPlayer1) before resetting the hit points. But it looks like no corresponding code for when you ARE player1
hmmm... no corresponding when I'm player1
and this is the video I showed
and even before that script. I hade that script https://gdl.space/bulividehi.cs which worked before but not anymore
Likely not an issue with that script then.
It's a bit hard to follow though. Lots of dependencies and allll those find calls
because like for example, it is still working for player 2, but now it doesn't work for player 1
hitpoints is like how much damage you take. PlayerHealthUI is supposed like to know that you took damage so that you lose a heart life in the health bar
what? now it's happening the same thing to player 2, I don't get what is going on anymore
if((nextRoom == 1 && spawnedRooms[(int)currentRoomPos.x][(int)currentRoomPos.y + distBtwRooms] != null) ||
(nextRoom == 2 && spawnedRooms[(int)currentRoomPos.x + distBtwRooms][(int)currentRoomPos.y] != null) ||
(nextRoom == 3 && spawnedRooms[(int)currentRoomPos.x][(int)currentRoomPos.y - distBtwRooms] != null) ||
(nextRoom == 4 && spawnedRooms[(int)currentRoomPos.x - distBtwRooms][(int)currentRoomPos.y] != null))
{
nextRoom = Random.Range(1, 5);
}
@leaden ice its giving me null reference error
i have to initialize the 2d array with elements
dipshit
you should use a 2D array
you did a jagged array so you'd have to initialize each subarray
2D array won't require that
this is where i got lost last time i did this
<@&502884371011731486>
i think this guy was trynna insult me
Sorry the "random insults" server is next door
dont be a smartass
Wrong server, still
show your code
Doubling down on this behaviour I guess
did you actually create the array??
if((nextRoom == 1 && spawnedRooms[(int)currentRoomPos.x,(int)currentRoomPos.y + distBtwRooms] != null) ||
(nextRoom == 2 && spawnedRooms[(int)currentRoomPos.x + distBtwRooms,(int)currentRoomPos.y] != null) ||
(nextRoom == 3 && spawnedRooms[(int)currentRoomPos.x,(int)currentRoomPos.y - distBtwRooms] != null) ||
(nextRoom == 4 && spawnedRooms[(int)currentRoomPos.x - distBtwRooms,(int)currentRoomPos.y] != null))
{
nextRoom = Random.Range(1, 5);
}
did you actually initialize the array?
ofcourse i didnt forget to make the actual array
I seems to noticed something like when I die and respawn, I noticed the player object in hierchy disappears
Nah they thought they were on the other server again
stop provoking me
I never said that
initializing would be a pain
reminds me of "I'm gonna release my bipolar"
yea and its not really a total grid based game
i dont know where the rooms will be spawned
You do instantiate a new one in code. Do you see it pop up at the bottom?
and then everybody clapped at your joke
it could go any direction
they're not spawned on a grid?
sure, but on a fixed grid, or no?
You can use Dictionary<Vector2Int, ROom> instead
your name? albert einstein.
or just HashSet<Vector2Int> if you only want occupancy
@gusty monolith You can stop now, thanks
hmm... yeah
whats the check for items in a dictionary
contains?
but no back full health, and that I cannot move and no capsule collider
I mean that have never happened before
Did you ever try to get version control?
@leaden ice
Thank you for the help! Although I'm kind of stuck now... I think it's because of the size of the miniMap camera? Since the player is able to control the size. The bigger the orthographic camera is, the more inaccurate the localPoint is
the local point shouldn't be related to the camera size. You need to convert that local point in the minimap to the world position it represents probably through some transformation with the minimap camera
like minimapCamera.TransformPoint(localPointFromClick)
wouldn't that happen to be organization adress type of thing?
Contains yes or if you want to actually get the thing you use TryGetValue
Nah man mine's on topic
I have no idea what you're saying here honestly
Ah but I see the mods were already here, I was scroll locked. I'll stop resurrecting the past conversations
aand to be honest, I usually only get permission from my dad unfortunately
You need an email address, that's it.
No need to pay anything or belong to some company or organization
if((nextRoom == 1 && spawnedRooms.Contains(new Vector2Int((int)currentRoomPos.x + distBtwRooms, (int)currentRoomPos.y)) ) ||
(nextRoom == 2 && spawnedRooms.Contains(new Vector2Int((int)currentRoomPos.x + distBtwRooms, (int)currentRoomPos.y)) ) ||
(nextRoom == 3 && spawnedRooms.Contains(new Vector2Int((int)currentRoomPos.x + distBtwRooms, (int)currentRoomPos.y)) ) ||
(nextRoom == 4 && spawnedRooms.Contains(new Vector2Int((int)currentRoomPos.x + distBtwRooms, (int)currentRoomPos.y)) ))
{
nextRoom = Random.Range(1, 5);
}
ok how could i still be getting a null reference
im using a hashset
what I mean is I only get permission from my dad to do stuff like this, like getting something
Where do you set spawnedRooms
did you initialize the HashSet?
i just added the vectors to the hashset when i spawn them
you have to actually create the HashSet
Where do you set spawnedRooms
roomPos = new Vector2Int((int)currentRoomPos.x, (int)currentRoomPos.y + distBtwRooms);
Instantiate(room, new Vector2(roomPos.x,roomPos.y), Quaternion.identity);
spawnedRooms.Add(new Vector2Int(roomPos.x, roomPos.y));
Okay but where do you set spawnedRooms
yep
spawnedRooms = new();
HashSet<Vector2Int> spawnedRooms = new();
All you did was declare a variable
you didn't actually point your variable at an object.
it works
but the logic doesnt
the code for checking if theres a room there i mean
could it be a rounding problem from my other vector2
should i use a vector2int for that
Yes you should be using Vector2Int all around
it must be something why it's becoming like this
because I am getting really panicked here
My top recommendation would be to stop until you are able to set up version control. That way you don't make more unrevertable changes that get you further from what you want
but wouldn't it starting to to cost after 1 month?
No
¨
use github as it doesn't need any cards on file
I have a lightning shaped line for my game
I try to make it turn in the direction the player swiped
I have 2 vector3 variables that show the start and end position of the swipe
And I'm trying to get them to turn into an angle
!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.
Every time I suggested version control I said use git and github, but they keep fixating on UVC 🤷♂️
You can also use git completely locally without a remote origin, and you will still get all the benefits of being able to branch/revert/etc.
float angle = Vector3.Angle(end_t, start_t);
transform.rotation = Quaternion.Euler(0, 0, angle);
You didn't answer the question about what components the thing is made of
