#archived-code-general
1 messages ยท Page 372 of 1
but it works on other objects
Oh it has an animator
i can delete
Maybe you have an anim clip playing that is modifying the root object's position
I'm stupid
thx a lot
Good, although you should still move it with rigidbody so you get correct physics
How do I achieve a realistic boxing fight in Unity? Like animations not clipping through the bodies, and I was thinking about animation rigging to stop the hand whentouching the body, but how cna I do that?
Is there a built in unity method for referencing other scripts variables by string? Like invoke, but for variables
No because it's not a good idea.
Perhaps sometime if I need to, but I think I have another way in mind. Either way, the gsame I'm making is incredibly lightweight so it won't have a performance impact.
Sounds like you're planning to use something way more complicated ๐ค
no no no, it will be really really simple, just a 2 minute implementation I swear!
As would a dictionary
I have given up, I'll learn a dictionary
Here's a simple example:
Dictionary<string, float> stats = new();
public void SetStat(string name, float value) {
stats[name] = value;
}
public void GetStat(string name) {
if (stats.TryGetValue(name, out float value)) {
return value;
}
return 0;
}```
And to use it:
```cs
myScript.SetStat("hp", 100);
myScript.SetStat("armor", 10);
//... later
float hp = myScript.GetStat("hp"); // gives 100
float armer = myScript.GetStat("armor"); // gives 10```
Camera.main.ScreenToWorldPoint(Input.mousePosition), DistanceVector,distance:Mathf.Infinity, grappleLayer
);```
I have this raycast, I wonder how to make it return only the first thing it hits and not the one the mouse touches at its exact location. does anyone know how to do it?
raycast only returns the first thing it hits.
now it makes sense, it starts from the mouse not from the point I wanted. Thanks
Does someone know why the raycast isn't drawing?
because you don't have any code that would draw anything
im watching a tutorial xd
if you want to see your raycast you can either (Debug.DrawRay) it or unity 2022+ there is a section in Physics Debugger for Casts
It doesn't matter if you're watching a tutorial or the Olympics or Lord of the Rings
you don't have any code that draws anything
If there is something being drawn in the tutorial, it's because they wrote code to do that.
in the tutorial they say that it is supposed to draw something
this line: RaycastHit2D raycastFloor = Physics2D.Raycast(transform.position, Vector2.down, rayCastDraw, floorLayer);
Only if you use the Physics Debugger Visualization stuff that Navarone mentioned
Otherwise, they've written another line of code
You need to do one or the other of those two
Can someone help with this?
maybe with physics ragdolls? It's going to be very complicated.
Take a look at TABS (Totally Accurate Battle Simulator) for example
No I don't want ragdolls and physics that much
But in undisputed, idk how they made it
Then it's going to be quite hard to achieve "realistic". Real boxing is all physics
Or in other fighting games
Not realistic particularly apologies, just the animation shouldn't clip through the enemy models when punching, and I think some inverse kinematics should be used, but I don't know in what way
Either active ragdoll as mentioned, or use something like a SphereCast along the arm and check if it is blocked by something. If it's blocked, use some IK to limit the arm
I'm pretty sure that those UFC/Undisputed games are using some sort of active ragdoll/physics animation
But thats ridicolously different from tabs
Right, any ideas about the IK?
I think if I use a single ik constraint I can limit the elbow stretched out no?
But for each animation I have to define a limit
I'm not too familiar with Unity's built in IK or any assets, I write my own
And what about uppercuts, that can be sketchy
Roger that
Yeah you might have to do some special cases for different moves. Like bending the forearm backwards (towards the puncher) when an uppercut hits. Or freezing/reversing the animation for a moment
This is going to be tricky to get right
TABS also most certainly uses some sort of active ragdoll
TABS is solely based off of active ragdolls
how do i make an object be able to get clicked on even if there's another object in the way?
Either make sure the object in front is ignored, or use some way that checks all the objects intersecting a ray.
how would I go about making the object get ignored?
That would depend on what method you use to detect it now.
well, its just a button, and the object on top just follows the mouse
A UI button?
Ui(assuming canvas ui), uses the event system and raycasters to detect the pointed objects. The object in front would need the "raycast target" disabled on its graphic component.
oh i see on image there is a bool for raycast target could I disable that?
well well well
Yes
Ui toolkit/elements for example. Or just a an object with a collider in the scene.
oh right
I have a question.
I am planning on doing a class select (barbarian, rogue, wizard, fighter) but i have my stats in a singleton like this
myHealth
myArmor
myDamage
myMana
i have some rough idea on the values I'm implementing based on the class selected so i was wondering if there is a better to assign values when choosing a class so i dont have to keep doing if (class == rogue) myStats = rogueStats and so on
is it inheritance, or something else
basically i dont want to have to type each specific stats for each specified enum
Why not just have the class type be part of the data object?
e.g.
enum AdventureType { Rogue, Barbarian ... }
class CharacterClass {
AdventureType adventurerType; // unfortunate
int baseHealth;
int baseArmor;
int baseDamage;
int baseMana;
}```
Make this into a ScriptableObject for example
Have you made any working project commits or backups recently?
presumably your project is corrupted in some way from the power outage
just a power outtage
nope
it's a pretty new project, haven't done backups yet
Then... you may be in a little trouble.
I would recommend making backups or commits frequently to reduce the risk of losing data to unforseen disasters
Why are you showing a screenshot of the build profile page
it's empty xD and messed up
yeah... :'v
hmm so nothing to do about this?
for hw i have to do singleton
but i did a switch statement
(wrong channel)
I don't see what a Singleton has to do with anything here honestly
Would definitely be a #๐ปโunity-talk question
I make the camera follow the player vertical position smoothly, but I have the problem that in some situations the player goes out of the camera's view. How to clamp these values?
if (actor.stats.isGrounded)
{
_tempTime = Mathf.Lerp(_tempTime, 0, SurgeMath.Smooth(1 - 0.925f));
}
else if (actor.stats.isInAir)
{
_tempTime = Mathf.Lerp(_tempTime, yFollowTime, SurgeMath.Smooth(1 - 0.9f));
}
_tempY = Mathf.Lerp(_tempY, target.position.y, SurgeMath.Smooth(1 - _tempTime));
_tempFollowPoint = target.position;
_tempFollowPoint.y = _tempY;
The heck is that abomination passed to Lerp as the third argument?
custom function
but how is this related to my question?
It's probably not. Just stands out as it's not a very correct way to Lerp.
You can clamp the _tempY to whatever values you want before using it.
but it won't work because the player's position is constantly changing
Why not? Calculate the correct range of values taking into account the player position.
var y = target.position.y;
var min = y - offset;
var max = y + offset;
_tempY = Mathf.Clamp(_tempY, min, max);```
i already did that, but thanks
I want to make a drop system that if i hold "Q" it will display an arc where the object is going to land. Something like in the image below. How would i achieve this?
separate the scene you are viewing and write down what systems are involved (ui, physics, input etc.) and come back with specific questions.
Yeah, break it down. A mechanic like that involves several different things like visuals, calculations, input handling, etc...
I used a line renderer to get the arc and using: https://www.gamedev.net/forums/topic/512304-good-throwing-arc-equation/
i got the formula and then assigned it to look like this:
void showTrajectory()
{
int trajectoryPoints = 100;
Vector3 direction = (Camera.main.transform.forward*5f)+transform.up;
Vector3 startPos = hand.position;
Vector3[] points = new Vector3[trajectoryPoints];
for(int i = 0; i < trajectoryPoints; i++)
{
float time = i * 0.01f;
points[i] = startPos + direction * time + 0.5f * Physics.gravity * time * time;
}
lineRenderer.positionCount = points.Length;
lineRenderer.SetPositions(points);
}
My throwing direction, the start position and then the formula and then setting the positions.
The line renderer though doesn't look the best.. so i'm trying to use a material, how do i make the material more visible? currently my scene is mostly all white because i don't have an artist and i haven't gotten to it yet. Any suggestions?
Change the line renderer/material color
Assign a texture
Maybe both
is it normal to have a lot of variables be assigned from the inspector?
mainly for the "game manager" script
yes, that is generally best practice
How much is "a lot"?
Assigning variables in the inspector is a good practice, but assigning too much variables is not.
for the game manager there are 10, and for some ui scripts there's like 5 each
that's not that many.. is it?
i thought it was
that's not unity related at all, so not the right channel nor the right server
this server is not a social hangout server, it is a help/learning server. there's no offtopic discussion allowed. #๐โcode-of-conduct
ok
ty
Nobody is going to guess a solution without some explanation on how you've implemented this.
ok i solved it
I have this:
[NonSerialized] public Vector3 velocity
= new Vector3(0,0,0);
when I do ctrl + s, it formats it to
[NonSerialized]
public Vector3 velocity
= new Vector3(0,0,0)'
I don't want that. I"m using VSCode and editorconfig. Can I disable this adjustment?
Open settings in VSCode (for me it is Ctrl + ,)
Type "format save" in the search field
You should see something like this
I do want format save. I just don't want that rule
Hello
I have an issue with rendering colors of my mesh, I created simple script that create grid and apply uv to each cell based on it's x grid position, but when I start the game the colors on my texture are much darker than on my texture.
this is a screenshot of my material
Try making it an unlit material?
I guess this is a good place as any. I need help with saving/loading yo json file. I think it may be the data I'm trying to save but It saves an empty dictionary.
I have my script. It's Firebase firestore. But I want a copy of player save data offline
Dictionary isn't serializable by unity. You need some sort of serializable dictionary, there are implementations available online
Or maybe other JSON packages can serialize it (Newtonsoft?)
It works, thanks
I'm saving as json
I know ๐ค
One second gathering materials
Please consider switching to Newtonsoft instead of JsonUtility. I assume that's the reason why it doesn't serialize
JsonUtility is very bad when it comes to serializing common types like this. Newtonsoft has a Unity package available and the syntax is almost the same
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โข Collaboration & Jobs
@hexed pecan and @thin aurora
Your saying that if it's my data types (because I do have a timestamp being saved as a generic object for firebase firestore) that json utility may not be serilizing it properly? I can try to use Newtonsoft.
There are some gamedev discords out there that allow you to search for collab partners (Game Dev League, Game Dev Network), I'm sure you can find them through discords server search
If you are using dictionaries, yes newtonsoft can help you, make sure to use the asset store version, the downloadable stuff through nuget or other sources crashes on ill2cpp builds
If you only have simple data types, JsonUtlity is totally fine, it would be nice to see the data structure you are saving
JsonUtility is unable to serialize a Dictionary, that's for sure. It also can't serialize arrays as the root object, and I believe Lists are also not possible. Lastly, for some reason it even can't serialize nullable types. These all work fine in newtonsoft
like specifically i didnt find any but its fine
So in short, it's not a good tool in the slightest. The only thing it has is that it's slightly quicker than the others
public struct SaveData
{
[FirestoreProperty]
public string User { get; set; }
[FirestoreProperty]
public string ProfilePicURL { get; set; }
[FirestoreProperty]
public int NumberOfWatchedAds { get; set; }
[FirestoreProperty]
public int CorrectAnswers { get; set; }
[FirestoreProperty]
public int WrongAnswers { get; set; }
[FirestoreProperty]
public float FastestSavedTime { get; set; }
[FirestoreProperty]
public int FiftyFiftyCount { get; set; }
[FirestoreProperty]
public int AudiencePollCount { get; set; }
[FirestoreProperty]
public int SkipQuestionCount { get; set; }
[FirestoreProperty]
public int PlayerGemCount { get; set; }
[FirestoreProperty]
public bool RemoveAds { get; set; }
[FirestoreProperty]
public object DailyRewardTimestamp { get; set; }
[FirestoreProperty]
public int SetBackground { get; set; }
}
Oh, right. It also doesn't serialize properties. So this struct will not work either.
Basically everything in .NET is properties when it comes to exposing data, rather than fields. It's just Unity that had to be special
So apart from some quirks with Unity types, Newtonsoft will always be the better choice
public object DailyRewardTimestamp { get; set; } why is your timestamp an object ๐
it has to be according to firebase to store on firebase firestore server
so def switch to newtonsoft and don't use json utility?
yes, newtonsoft is also a drop in replacement, i think you only need to change the import and you are fine
If you want an easier time developing without constant workarounds, then yes
Technically you can work around the issues but this is a lot of extra code and bloat
dont reinvent the wheel ๐
No, obviously. I'm just saying that it's possible
ok , I'm downloading newtonsoft
I can't fint the asset store version , I found the git version
dont use the git version
if you download it from git it doesnt containt the fixes for some build targets
got it added by name in package manager , the git has instructions , thank you
Version 3.2.1
ok seems that json utility was the issue
the following screenshot shows thqat it's now filled with data and not empty
I'll just have to remove the image url and the timestamp maybe or convert them to a proper data type before saving like a string
is that.. wordpad? ๐
https://code.visualstudio.com/ cough even fine to use as a text editor replacement
I'm trying to make a system where a signal travels outwards at the speed of light, and then various telescopes around the universe can receive it. My first thought was to use colliders and detect when they collide, but setting the size of a sphere trigger via script (for the signal), it doesn't detect when the telescope starts being inside. I'm considering using a list of signals and just iterating over it every once in a while to see whether telescopes can detect the signals, but that seems inefficient. Does anyone have any ideas for how to make this work?
track size of signal "bubble" + distance to telescope, unitys physics system sounds like a horrible usecase for this
if the telescopes do not move you can even just build cache where it tracks the object + their distance per source and then "ping" them once your size > distance, no need for distance checks every frame
๐คฃ Yeah , throwback !
Makes sense, would it be a good use for coroutines?
just run the check in update, no need for a coroutine
comparing two floats (size and cached distance), even going through a list of hundreds of them and comparing each is not a performance concern
unless you want millions of telescopes and thousands of sources, then i would think about optimization ๐
Thanks!
Hello, I have this code and what happens to me is that if I don't click on the perfect microsecond, the attack doesn't come out. Is there a way I can make it so that if I click while waiting for the second one, it will be saved and the next attack will be made?
sorry if my english is bad
not with WaitForSeconds...
You would change that
make a loop and yield return null to wait one frame in the loop
and use a timer and check the input every frame until the time elapses
e.g.
float waitTime = 1f;
float timer = 0;
bool inputPressedInTime = false;
while (timer < waitTime) {
timer += Time.deltaTime;
if (Input.GetWhatever(...)) {
inputPressedInTime = true;
}
yield return null;
}
if (inputPressedInTime) {
//...
}
else{
//...
}
Something like this?
I'm trying to make a chess game, and I'm currently designing the subsystem that I might need. I've come up with this following: grid, piece, input, logic-rules, game state, ui, ai. My first goal is to make a grid and make a pawn class to move all around the board. My questions are:
Does this approach seem decent?
Any information anyone has on making a reusable grid system?
Anyone willing to give an idea of how a piece would communicate with the grid?
I'm not sure I understand the bottom half but - yes, I provided an example
ok, thanks. Ill try it
sorry if my english is bad
Hi, I'm working on a game with hitboxes in 3D space, and I've created Hitboxes as Monobehaviors with Colliders and such. I've programmed the hitboxes to update transform properties to hardcoded values on a per-frame basis (position, rotation, and scale). My question is, is there an elegant way for me to store the transform transformations? Could I come up with something better than the following?
[SerializeField] public Vector3[] positions;
[SerializeField] public Quaternion[] rotations;
[SerializeField] public Vector3[] dimensions;
private Transform Origin; // the <typeparamref name="Transform"/> about which the hitbox is anchored
private int Frame = 0;
// ... more member fields
void FixedUpdate() {
// ... abbreviated snippets in FixedUpdate
Vector3 offset = positions[Frame];
transform.position = Origin.position+Origin.rotation*offset;
// ...
Frame++;
}
Basically, the arrays of Vectors hold the new transform state on each frame. I might consider some sort of struct that tracks all ~9+ values into one array element, but as I understand, Transform can't exist independent of a GameObject.
Im not really sure why you need this, but if it solves what you need then I'd consider this fine. The only different thing you could do is store the 2 Vector3's and a Quaternion in your own TransformData (or whatever name) class. I wouldnt use a struct here
how can i write like that?
this
!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.
Hello!
The problem here is:
When i interact with my pc, i go into the new camera, but when i want to exit it, i can't, using e is not working. And also i don't have any idea why, but this error is showing, despite everything assigned. It might have something to do with raycasting....
Interaction.Update () (at Assets/Scripts/Interactions/Interaction.cs:23)```
Line 23 is this:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);```
this almost certainly means you don't have any MainCamera in the scene
(It needs to be an object with a Camera component and the MainCamera tag)
this is not relevant to the error
oh, so thats why it triggers when i go into pc camera
in this moment i disable main camera
then you shouldn't be trying to do raycasts from the camera while it's disabled
yea, i can as well disable it
its not usefull for pc camera anyways
but ok, so i fix it by just giving pc camera main camera tag?
It really depends what you're trying to do
The better solution here is probably to use Cinemachine, because then you only have one camera in the first place
But you could also manage your references to the different cameras
I have interaction with many things like doors. When i interact with a PC, it is supposed to go on closer look to monitor screen.
Do you need interaction behavior to still work in that mode?
I doubt it
so you can just check if either you're in that mode or if the camera is null
and return early
or just disable the interaction script while in that mode
lots of options
So the expected behavior is: I click e on pc, i get in the pc camera, i press e again, and i switch to normal camera once again.
I can disable raycasting and interaction while im using computer.
I can give my pc camera main camera tag
when i give maincamera tag to the computer camera and the actual main camera then my raycasting goes to shit
well yeah it will pick one at random
IDK why you would do that
you don't want to raycast from the computer camera
No, i don't need raycast or interaction when im on computer mode. All i want is to be able to switch through the cameras
can i make the camera not usable but not disabled per se
again the best way is to use cinemachine
instead of multiple actual unity cameras, it uses just one camera and a bunch of "virtual cameras"
Then you won't need to worry about this as there is only ever one MainCamera
hmm, ill look into it, i used it 2 years ago, but i long since forgot what it did
I have an enemy that when it moves its supper jittery
Idk why
It's not to do with fixed update or anything everything is on regular uodate
You're probably using a Rigidbody without interpolation
or you're breaking the Rigidbody's interpolation
You'd have to show your code and show the object's inspector
Wdym
Not sure what's unclear about that exactly
My rigidbody is set to interpolate
but a Rigidbody moving without interpolation will move at the physics update rate
Well - your code is likely breaking the interpolation then
Can you please share your code
Sure
It's a bit big xuz I worked on it a bunch on my old pc where.my frames were so low that I didn't see the jittering
๐ 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.
I'll send the smaller code in which this happens
here
Thank you
Your problem is here:
if (rb.velocity.x > 0.05f)
{
transform.localEulerAngles = new Vector3(0, 180, 0);
}
else if (rb.velocity.x < -0.05f)
{
transform.localEulerAngles = new Vector3(0, 0, 0);
}```
because you are directly modifying the object's Transform each frame, it is breaking the interpolation you set up on your Rigidbody
Can you show:
- The inspector for this object
- How your camera works?
(do you have a camera that moves?)
Can you show that script as well?
and this
nvm i relazid what i did
i had another script also enable that was messing everything up
how can i flip my player in my script without directly changing its tranform?
well you can change the transform - i just would recommend not doing it every single frame
only do it when you change directions
I'm using Vector3.RotateTowards to have 8 directional rotation from my arrow keys by using this function:
Vector3 vector3 = Vector3.RotateTowards(transform.parent.transform.localEulerAngles, targetVector, 0.05f * Time.deltaTime, 0.5f);
transform.parent.transform.localEulerAngles = new Vector3(0, 0, vector3.z);
What's the easiest way to adapt this function to not take a long way round when wrapping around over 360?
ok!
RotateTowards is for direction vectors, not euler angles
basically - doing anything with euler angles is usualkly a mistake
I would not use euler angles
I tried using quaternions but it caused a lot of problems due to needing to go over 180
you should do something like this instead:
Vector3 currentDir = transform.parent.up;
Vector3 targetDir = /* whatever 8 way direction vector you want */
transform.parent.up = Vector3.RotateTowards(currentDir, targetDir, Time.deltaTime * .05, 0.5f);```
You don't need quaternions
but quaternions would also work just fine here
not sure what you mean about "needing to go over 180". Those are the woes of someone using euler angles
I spent 4 hours last night shouting at quaternions so aren't really in the mood for any more of them
well my suggested solution doesn't use them so
Yeah, thanks for that
This is what was happenign with Quaternions, it refused to be anything other than 180
"with quaternions" is really vague
it would be an issue with your code
Slerp'ing between the target and beginning rotation then applying the result to the parent rotation
There was somethign going wrong with it but couldnt figure out what
Showing the actual code would be much better than describing it, but - it's moot at this point
Yeah I would but it's long gone
[RequireComponent(typeof(CharacterController))]
public class Movement : MonoBehaviour {
public Vector3 velocity = new(0, 0, 0);
public Vector3 acceleration = new(0, 0, 0);
public CharacterController controller;
public void accelerate(Vector3 force) {
acceleration += force;
}
private void Start() {
controller = GetComponent<CharacterController>();
}
private void Update() {
velocity += acceleration * Time.deltaTime;
acceleration = new(0, 0, 0);
controller.Move(velocity * Time.deltaTime);
}
}
[RequireComponent(typeof(Movement))]
public class Gravity : MonoBehaviour {
[SerializeField] float rate = 9.81f;
[SerializeField] float terminal = 53.9f;
private Movement movement;
private void Start() {
movement = GetComponent<Movement>();
}
private void Update() {
if (movement.controller.isGrounded)
movement.velocity.y = 0;
else
movement.acceleration.y -= rate * Time.deltaTime;
if (movement.velocity.y > terminal)
movement.velocity.y = terminal;
}
}
so its like
Gravity -> requires Movement -> requires CharacterController
@hexed pecan
you reset it's downward acceleration every frame
which means, unlike real gravity, it does not actually accelerate
i reset acceleration but not velocity
acceleration represents forces so you typically zero that every frame
because you can't assume that a force is constant
gravity could be turned off the next frame
or, the engine thruster to the rocket could stop being pressed on the next frame
so accel always gets assumed to be zero at the beginning/end of frames
okay sure, and what actual debugging have you done to ensure the values are what you expect them to be?
i assumed i must be doing something obvious like an extra delta time somewhere
wanted to see if anyone could see it easily
if you have some idea of what it might be, why not test that theory instead of asking here?
what would i test
the delta math is hard for me right now
if anyone sees an obvious bug that I can fix, that is much much faster
Hey, I'm adding throwing to my topdown game and my math is not mathing
Vector3 mousePos = _cam.ScreenToWorldPoint(Input.mousePosition);
float distance = Vector2.Distance(transform.position, mousePos);
if (distance > MaxThrowDistance)
{
distance = MaxThrowDistance;
}
float horizontal = Mathf.Clamp(MaxHorizontalVelocity.y * (distance / MaxThrowDistance), MaxHorizontalVelocity.x, MaxHorizontalVelocity.y);
float vertical = Mathf.Clamp(MaxVerticalVelocity.y * (distance / MaxThrowDistance), MaxVerticalVelocity.x, MaxVerticalVelocity.y);
ItemObject thrownItem = _mapManager.SpawnItem(_selectedItem.Item, _hand.transform.position.x, transform.position.y, 1, ItemObject.ItemState.MidAir);
thrownItem.Throw(_hand.transform.right * horizontal, vertical);
flying obj:
private void UpdatePosition()
{
if (!_isGrounded)
{
_verticalVelocity += _gravity * Time.deltaTime;
_sprite.transform.position += new Vector3(0, _verticalVelocity, 0) * Time.deltaTime;
}
transform.position += (Vector3)_groundVelocity * Time.deltaTime;
}
private void CheckGroundHit()
{
if (_sprite.transform.position.y < transform.position.y && !_isGrounded)
{
_sprite.transform.position = transform.position;
_isGrounded = true;
GroundHit();
}
}
The idea is to throw item and make it land exactly at mouse pos. If mouse pos is outside the range then it should throw it as far as it can within the range towards the mouse.
It should fly along a parabola.
if you think it is an extra deltaTime multiplication that is something you can super easily test considering there are only 3 there.
that worked thank you
Im making Config Singleton (this script is attached to GameObject)
While Debug.Logs returns correct values on Awake later when i try use anywhere (in same namespace) like Config.Instance.AppRoot it returns empty string
using UnityEngine;
using System.Runtime.CompilerServices;
using System;
using System.IO;
namespace RPG
{
public class Config: MonoBehaviour
{
public static Config Instance { get; private set; }
#region app
private string version = "0.1";
// private string appRoot = Application.persistentDataPath;
private string appRoot = Application.persistentDataPath;
public string Version
{
get { return version; }
}
public string AppRoot
{
get { return appRoot; }
}
#endregion app
private void Awake()
{
if(Config.Instance == null)
{
Config.Instance = this;
Debug.Log(Application.persistentDataPath);
Debug.Log(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData));
Debug.Log(Application.productName);
}
else
{
return;
}
}
}
}
if(Config.Instance == null)
{
Config.Instance = this;
????????????
whats wrong with this?
singleton shenanigans no?
thats how u make sure that there is no coppies
why would you refer to the class you are already in?
that's the singleton pattern
if there's another instance
then this won't replace it.
There can be multiple instances of the class. This ensures that it doesn't say I AM NOW THE SINGLETON when there already is one claiming that title.
sure accessing it through the class instead of just Instance == and Instance = this within the class is a little unconventional, but it's perfectly fine
you spammed ? as if they made a grave mistake
what he did shows a fundamental lack of understanding of what he is doing
it really doesn't though
it really does
i hope you are joking
how? it's literally the same thing but with more typing required. it isn't wrong, it's just unconventional. it's like typing this. before everything within the object. it isn't necessary but it also isn't incorrect
no I am not, why would the Config class refer to the Config class explicitly?
it literally doesn't matter though, it compiles to the same thing so what difference does it make if they want to get a little extra explicit about it?
I know it doesn't matter as far as the compiler is concerned, I'm just saying it demonstrates a lack of understanding
it literally does not. Being more verbose doesnt mean u dont understand how something works
in this case I would beg to differ, he has obviously learned that static variables should be identified by the class name and has applied that here without knowing WHY that is the case
Yeah i lately start to rewrite many classes to use explicity to what class i refere cause whiele my project is fast growing with many files classes its start to looks so messy to call thousend of function from diffrent classes, so while im jumping every 10s between files to find something or extend it it makes way more obvious where it cames from, on what i work
And its all compiled so its doesn't really matter for optimization
Nah its not true i had wroten hundred of files without pointsing from which Class it comes as it was in same class or namespace but while im jumping all over it in midnight when I'm sleepy it makes a lot of sense to see on what I'm working
also atleast for me it make sense to write Class.staticprop
Instead just access static prop to keep clean diffrence between local properties and static or from object
to come back to your question, you cannot use Application.persistententDataPath in a class constructor
try
public string AppRoot
{
get { return Application.persistentDataPath; }
}
and forget appRoot completely
I see thanks i found work around with dependencies and scripts order but that would be such a overhead for just getting path
note that if you need to access that on another thread you need to go back to having a field for it, but make sure to assign to the field inside of Awake rather than the field initializer
or an auto-property with a private setter
True, just didnt knew that i cannot use unity dependiencies on constructors like Steve said
interestingly it will only throw an exception if you do try to use it outside of the main thread
Well i didnt even got any log message just got empty string ๐
yep, bad Unity error handling
Heya people, can someone please tell me how to make a Graph in script (like a one in trail renderer)?
Wait what does trail renderer have to do with graphs?
You want to draw some lines or?
I guess the animation curves in inspector?
I can't get the freaking shape to stay in the mesh filter..
anyone have any clue what I am doing wrong.. I have the shape, and I assign it to the mesh filter... but i get this
MeshFilter and Mesh assigned.
Mesh was reassigned to MeshFilter.
Vertices count: 202
Triangles count: 600
Mesh was reassigned to MeshFilter.
It is supposed to reveal the FogOfWar.. but the mesh wont stay
What shape? What are you trying to do? wdym by the mesh staying?
if i put a cube on it... it works
The shape is being created from the raycasting and changes dynamically
ok... so, show your code?
// Ensure mesh is updatedd
if (meshFilter.mesh != visionMesh)
{
Debug.LogWarning("Mesh was reassigned to MeshFilter.");
meshFilter.mesh = visionMesh;
}``` This part isn't necessary tbh
you are assigning it in Start
When you say it "won't stay"? When does it "go away"?
it never reassigns
I took that code out you mentioned.
so it get assigned.. but since the shape is dynamic cuz it is made with rays. I am guessing it gets cleared?
What is it printing in terms of the triangles and vertices?
does it keep printing reasonable numbers each frame?
looks fine
What material are you using?
My guess is that your problem is probably related to the fact that you are never assigning any UVs to it
What are you expecting it to look like?
I want it to cut out the shape based on what you see in that picture
as the player moves the shape will change
I understand that
The material and shader are correct because once I put a different mesh filter on it. the transparency works
so the UV thing is probably somethng i need to look into
one thing you're doing wrong here btw is that the vertex positions need to be in local space
So unless this object is always at (0,0), things are going to be off
crap
Oh actually
I think you're handling that properly
because you're doing vertices.Add(direction * hit.distance); instead of hit.point
it won't account for scale properly though
it would be better to do vertices.Add(meshFilter.transform.InverseTransformPoint(hit.point));
Ok, and you mean for scaling.. like different resolutions ?
no i mean if your object is scaled
like Transform scaling
or rotation
which may not be something you plan on doing
Oh ok yeah rotation as the player moves and looks, so that could be an issue
So you are thinking since the mesh filter clear should be removed? or how can I keep the shape to dynamically update like I am trying.. this has been a headache its been a few days of messing around and I keep starting over.
Feels like it shouldnt be so hard..
You mean the visionMesh.Clear part? That should be fine since you are assigning the verts&tris after that
Whats the issue again - does the mesh appear invisible?
You're right.. I have a dynamic shape.. but it wont stay in the mesh filter i think is the issue... so the screen is black. The transparency is working correctly though cuz when I put a cube there I can see through.. Praetor made mention it could be a UV issue?
If its an UV issue then it should be an easy fix - just add a UV coord for each vertex, they are already in 2D space
Do you think that is why the filter is blank? I am newer to this.. this probably would have taken most of you a few minutes lol. its been 3 days for me now
I mean using the same vectors for UV as for verts
Blank? You mean the value in the Mesh field of the meshfilter?
You didnt give a name to your mesh
So it just looks like it is blank
Oh ok. makes sense
That is bad practice lol cuz it confused me
Ok.. so UV is what i need to look into, thank you both for your help
you think that is the main issue correct?
Not really, except if your shader uses UVs
Also make sure your triangles are not upside down
From a quick glance at the code I think they should be upright tho
You can create the UVs very similiarly to how you created the verts
Hey,
I'm having an issue with rotating a turret towards a target angle.
The turret is supposed to rotate at a fixed traverse speed in degrees per second.
Clamping the rotation speed leads to the turret traversing with an easing towards the target angle when delta angle is smaller than the traverse speed.
This means that the time to traverse towards the target angle is far longer than it should be. This leads to the turret not being able to aim for first order intercepts or any moving target.
Making the rotation speed always the maximum with the sign of delta angle leads to the turret always rotating at traverseSpeed * Time.deltaTime. This means that the turret traverses over the target angle this leads to oscillation that throws off the turrets aim. Besides not being desired behaviour.
How to calculate when this oscillation will occur and subtract it from the traverse amount?
Here is the logic for calculating the traverse amount that later in its lifetime will be inputted to Transform.Rotate.
// this is the target euler angle for the turret
float targetAngle = -targetEulerY;
// turrets euler angle
float turretAngle = -turretTransform.eulerAngles.y;
// Calculate shortest angle between target angle and turret angle.
float deltaAngle = Mathf.DeltaAngle(targetAngle, turretAngle);
bool deltaAngleIsPositive = deltaAngle > 0;
// get current maximum traverse speed deg/s
float effectiveTraverseSpeed = EffectiveTraverseSpeed;
float traverseSpeedPerFrame = effectiveTraverseSpeed * Time.deltaTime;
// Clamp angle to set fixed rotation speed
float traverseAmount = Mathf.Clamp(deltaAngle, -effectiveTraverseSpeed, effectiveTraverseSpeed);
float deltaAngleSpeedPerFrame = traverseAmount * Time.deltaTime;
// Get maximum traverse speed by checking if delta angle was positive.
traverseAmount = deltaAngleIsPositive ? effectiveTraverseSpeed : -effectiveTraverseSpeed;
float maxTraverseAmountSpeedPerFrame = traverseAmount * Time.deltaTime;
// Calculate turret's angle next frame
float turretAngleNextFrame = turretAngle + maxTraverseAmountSpeedPerFrame;
// Get signs for comparison.
int aSign = deltaAngleIsPositive ? 1 : -1;
int bSign = Mathf.DeltaAngle(targetAngle, turretAngleNextFrame) > 0 ? 1 : -1;
// will over compensate with traverse speed if the signs are not equal and if used delta angle input is smaller than traverseSpeedPerFrame.
bool overCompensatedNextFrame = (aSign != bSign) && deltaAngleSpeedPerFrame < traverseSpeedPerFrame;
if (overCompensatedNextFrame)
{
return 0f;
}
return traverseAmount;
This logic does not remove the oscillation.
I would use quaternions and Quaternion.RotateTowards to achieve a linear rotation towards the target
euler angles are a recipe for disaster
I got it to let me see though a little bit at least. Gotta keep messing with this and refine it.. but thank you both for the help. at least I know I am in the right ballpark at least..
The targetEulerY has always taken the turrets euler angles in to consideration.
So the delta angle is always correct.
This more of a question of calculating the oscillation.
Here is a log about the oscillation:
deltaAngle=0.511673deg
deltaAngle=-0.7049866deg
deltaAngle=0.538147deg
deltaAngle=-0.6224365deg
deltaAngle=0.6960449deg
float newAngle = Mathf.MoveTowards(currentAngle, targetAngle, speedInDegreesPerSecond * Time.deltaTime);
the euler angle is still problematic though even if you do DeltaAngle
because an euler angle cannot be taken in isolation
you might get (0, 180, 0) or you might get (180, 0, 180). Those are equivalent
and if you only are looking at a single axis (y) you will not note a difference at all between (0, 0, 0) and (180, 0, 180)
So - I'll warn again against reading euler angles from the Transform and acting on them - it is a pitfall
Yeah I've moved on from reading euler angles in my code. This is unfortunately the only area of my project were I haven't got to refactoring that yet.
Could also substitute it with Vector3.SignedAngle(Vector3.forward, turretCurrentForward, Vector3.up)
If im thinking straight ๐ค
What is this calculating?
The angle of the turret's forward along the world Y axis
From Vector3.forward which I would consider zero
Cool, I'll put that in my vector math struct
So basically eulerAngles.y but without the issue that Praetor mentioned
So whenever I start my game, it crashes the editor (or built version) and closes it completely. How can I determine what causes this?
Since I don't have a console to look at
you can look at the !logs
could anyone suggest a efficient/performant to create a melee telegraph in unity 2d? Im trying to create something like a red area that follows a physics.overlapcircle
would the best way to do this just be by instantiating a object with some image or would linerenderer or something like that be easier?
hard to explain but
i want to spawn my spaceships at my shipyard's spawnpoint transform, at the furthest/rearmost point of the ship, so when spawned, the furthest point of the back of the ship is at the spawn point, so it doesn't matter how big the ship is it always fits and points away from the spawn
How do you guys make GUI with code?
Imo it's better to set it up manually in the hierarchy window, using code just for things like animations,interactions, updates based on gameplay etc
Like use the prebuilt GUI system, then handle events programatically?
Yeah
KK, I haven't delved much into it yet, as I'm still learning the basics of Unity, but I did attempt it awhile ago and could not figure it out lol
I've made some games in gamemaker2, and javascript using HTML/CSS, Unity is much more complicated haha
But you're not restricted to just events, like for example you can have a script on the panel that will resize on app start to fit screen width of the device or smth, but it is nice to have "a base" that was set by prefabs
Right
I was also curious about player animations, how do people usually handle those? programatically or using the GUI Unity has provided
That depends. For things like making a game object floating in space based on simple sine wave it's easier to do with code, but for skinned meshes and blending there's a whole workflow on animator components
Damn, Ill worry about animation after I get all the basics down then xD
Iirc the very first of catlikecoding (which I highly recommend as it is gold) tuts covers both the basics of unity gameobjects and animating them via code to make analog clock. Learning about animators, state machines and stuff can be done later preferably
But for basics there is plenty of other valuable tutorials on yt and unity page
kk, I prefer to learn by doing xD, I'm too adhd to follow tutorials
If you crazy enough you can try diving into DOTS immediately, before you get to much OOPed by MonoBehaviors ;p
I can read stuff, just people talking at me, youtube tutorials not the best
Got it
Maybe its just all the ones I've seen suck, theyre way too fast or way too slow
Either way though I prefer reading lol
Ill check em out anyways
Well, catlikecoding tutorial is text based, check it out fr
Okay great, I will
Drag and dropping in editor with UGUI will get you pretty far, only when you are doing highly dynamic and complex UI that you will want to use code only.
I just enjoy writing code for everything, I love coding xD, I find programming easier than using UGUI
UGUI is usually confusing on what certain things do, and code is just solid in what it tells you it does
Can anyone tell me how to manipulate line renderer material in run time I have a project to show and can't figure it out
https://catlikecoding.com/unity/tutorials/ is this the correct website?
Yes
You might also want to check out UI Toolkit, it's very similar to HTML/CSS (but Unity flavored).
Awesome, it would probably make a lot more sense to me off the start then lol
It's aiming more at art in later tutorials, but "Basics" section cover programming pretty well
I also have good amount of experience in web dev and yeah, UI in Unity, especially UGUI and drag and dropping like a caveman, is so painful in comparison. But it's good enough for most cases and gets the job done, because game UIs usually aren't that complex comparing to web/desktop apps.
Personally I prefer to write code for UI as well, but UGUI is intuitive as walk in the park and letting you make simple things waaaaay faster
Maybe having a big tolerance after messing with crappy UEFN gui though xd
Yeah I wasnโt sure whether to learn unreal or unity for my first 3d engine, so far I think Unity is pretty good.
Just difficult starting out, same as any engine really
For me the choice is pretty simple. If you prefer manual gearbox go for unreal unless you have poor hardware or want to make "simpler" apps
Everyone I asked told me Unity gives you more freedom vs unreal
Like unreal lays out everything for you more
Not really sure what they meant, because I have no idea what the difference between them is lol
Well it may be true if talking about Editor. But when it comes to programming language, C# handles much more things automatically. Whether it is good or not it's a matter of preference
Ah I see what you mean
I did read that can be an issue when trying to configure networking eventually, or garbage collection
But even then, arenโt you able to change the functionality of those things? Or are they locked. Iโm still a noob
Forget about networking for at least the first month of learning unity :p Messing with GC is unsafe advanced kind of thing, that you will use rarely when working with unmanaged low level stuff that is also not a topic for beginnings
But you ARE able to change those things?
So if you want to, you can, it will just take some effort
Yeah, you can do pretty much everything you want in the engine
Some lower level stuff could be probably achieved way easier with CPP though
Yeah definitely
If you choose to program in c++, how could you configure that in Unity, or is it not possible?
Ugh... I think it's something about Native Plugins if I'm not wrong, but didn't do any research on the topic tbh
Just stick to C#, it will drive you all the way basically
Kk
I think itโs good for me to learn anyways because my education teaches me c++ but not c# lol
C# seems extremely similar to Java so far
Unity provides quite safe API like UnsafeUtility to work with marshaling, so you can basically forget about c++ at all, at least if you don't write .dlls in it
But again - didn't do things like this in unity personally so maybe wrong
Kk thankyou for your time sir
Np uw
Im going to checkout those resources in the morning, Iโm burnt trying to figure out this python project for school, Iโm making some game similar to minesweeper lol
Iโm learning python while trying to make it, so the syntax was holding me back for ages
Sometimes I wish we had that machine from the matrix that just downloads the mastery of a skill into your brain lol
But then there probably would be no reward or gratification to learning anything
You can also bet it's gonna be expensive as hell.
Might be cheaper to hire a gamedev company to develop your game instead.
Hahaha youโre right ๐
I seriously think programming is one of the coolest things Iโve ever discovered, and I want to know all of it, Iโve been programming for just over a year and a half and moved my entire hobby/ future career this direction. It feels like such a slow process getting into it though. Especially when I see people around my age online writing entire game engines (actually now that I think of it, itโs usually guys 30+, Iโm 24)
But everyday Iโm so motivated to learn more, if I donโt get into an adhd hyper focus hole of grinding some game
Iโll fire up Unity and just try to understand basic movement and physics tweaking code slightly for like 6 hours each day lol
If I donโt have assignments due ugh
I sometimes wonder if Iโm studying it all wrong, and thatโs why it takes me so long
maybe its not a common statement, but i think writing entire engine from scratch (provided you know the language and have a good plan) can be just the same challenging as learning ENTIRE unity api, because it is just huge. So 3 steps forward - 2 steps back - do research - repeat is a good way to learn it, if you aim to be more generalist than specialist. Otherwise just master a single skill before switching to the next
Thankyou sir
This discord is great, Iโll definitely be in noob help a lot lol
Is there any way to get the current shadow distance that is set?
Ah found it QualitySettings.shadowDistance;
Try the non coding channel #๐ปโunity-talk
I have a tilemap, that i'm placing my buildings on, now the problem is, that the buildings (fences in this case) that are further away in the tilemap, overlap with the ones that are closer to the camera, making this effect. Any ideas how I should approach this?
I think this will help you https://discussions.unity.com/t/sorting-layers-according-to-y-axis/153125/2
Hi all, when using Unity Gaming Services for User Authentication with user/password, is there a way for the user to recover the password in the case of forgetting it? I can't find in the documentation.
Can someone explain me why this shows like its wrong?
It should look like this i think...
you probably have not installed the Input System package
teh red squiggle means you have a compile error. Mouse over it to read the error
or look in your unity console
It seems so
i hadn't installed it yet, thanks!
guys is there a way to modify a value declared outside of a corroutine
when changing the parameter value that is tied to that outside variable ?
Can you show an example of what you mean?
and explain what the end goal is?
sure gimmie a sec
x = 1;
Ienumerator corroutine(int var){
var = 90;
yield return null;
}
void update(){
StartCorroutine(corroutine(x));
}
idk why the outside value doesnt change
isn't it supposed to change when used as a paremeter ?
int is a value type
value types are pased by value into functions. aka a copy is made
no, it is passed by value not reference
oooohhh
this has nothing to do with coroutines btw
the coroutine is a red herring
It's the same for any method
yeah i kinda have no idea what to even search in the net
Search value types vs reference types in C#
instead of doing
int x = 1;
do
int[] x = new int[] { 1 }
then you can pass that array by reference
the way to do this would be this.x = 90 or pass a reference to whatever owns x if it's not this
damn thank you both very much
Im doing a "Combo System" for my game, i've reviewed all the code and the only part that doesn't works is this. It doesn't receive the input. I tried putting "Attack()" in the update, removing it and changing the input and it doesn't work. Does someone know why?
I mean you're not actually calling the Attack method
Have you tried actually calling it?
what do you mean "calling"?
void Update() {
Attack(); // << this is how you call a method
}```
yes
and it doesnt work
in your screenshot here, you are not calling it
what doesn't work
calling methods works, I can assure you of that
bc i removed it
wait 1 second
instead of just logging the outcome, log ALL of the steps in your code
mp4 please to embed in discord
ok wait 1 sec
but what is a video possibly going to show here
all this code does is set a couple of bools
that i call the method in update
That's not all of the code
Can Receive input is false, so your if statement won't pass
you need to debug your code
Start using Debug.Log more and print values out and test your assumptions
Im doing a "Combo System" for my game, i
is there a way to read out the speed that an animation is played back at while the animation isnt currently playing?
I am trying to Invoke something after the duration of an animation and I want to be able to adjust playback speed without needing to adjust the script each time.
I am trying to Invoke something after the duration of an animation and I want to be able to adjust playback speed without needing to adjust the script each time.
For this the best way is to use an animation event
Is there any other way to do this? cause I am trying to avoid the animation events because of reasons too long to explain here.
Guys, I'm building for mobile, is there any way to increase the scroll fps of scroll view? It's scrolling at 30fps and looks choppy
Thank you very much, I will have a look into that!
If anyone knows please do tag me
The scroll view is never smooth, but one thing you can do is ensuring you using canvas groups and not causing unnecessary redraws. Learning how to optimize the UI is a whole thing that you can look into:
https://unity.com/how-to/unity-ui-optimization-tips
Additionally, if you're scrolling through a lot of repetitive content (like leaderboards, etc.), you can object pool and reuse objects.
I see, I'll look into it. But is there no way to actually manipulate the scroll fps or something?
I mean, I'm running it on s24 ultra, it should be running ultra smooth if I understand correctly
Unity's UI is extremely bad performance in general
There is a lot of overhead that happens, which is why you have to optimize it as much as possible by ensuring you're not doing anything unnecessary (refer to the link)
Also the UI fps is not separate from the game fps. If the game runs at 30 fps then the UI runs at 30 fps. The default framerate is 30 or 60 on many mobile devices
!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.
Hey guys! I need some help ๐
So I want to have different Cards with different effects in my game. I started by creating a Card Scriptable Object that has different Data and my idea was to have a property of type CardEffect where I can assign different Classes of type CardEffect that derive from the main class CardEffect and implement the method UseEffect(). Now I want to create CardEffect like "DealDamage" where the amount can differ from card to card and I want to be able to assign the damage value when I assign the CardEffect to the Card-Asset from the Scriptable Object.
Hope that was clear.. ๐
Hey, general question about formatting... I have a bit of code I was thinking of refactoring into a switch statement, just wondering if there is a general consensus of weather if else chains or switches are nicer no only for writing but reading as well.
Let me know what you think of both sample, and yeah I'm aware of the errors
A: https://paste.ofcode.org/hy59krVP2MpwDSXKTLEHWp
B: https://paste.ofcode.org/pVUU2KWSJaCmHb9GXPgFZG
the if/else chaing you have there is way less performant and produces a ton of garbage
at least make an intermediate varaible first
string tag = obj.tag;
if (tag == blah || tag == foo)```
every time you call obj.tag it allocates a brand new string, which needs to be garbage collected
oh thats awful
I would say the switch statement is better in either case
switch cases not having their own scope is one of the weirder things I've learned about C# in a while
you can pretty safely give them a scope with { }
is that supposed to be a pun
hahaha
just feels wrong
blame C, C# inherited it from that!
it's the same in C++
The instance ID of an object acts like a handle to the in-memory instance. It is always unique, and never has the value 0. Objects loaded from file will be assigned a positive Instance ID. Newly created objects will have a negative Instance ID, and retain that negative value even if the object is later saved to file. Therefore the sign of the InstanceID value is not a safe indicator for whether or not the object is persistent.
So, can we distinguish between dynamic spawned gameobjects and preloaded gameobjects by checking sign of instance id?
Therefore the sign of the InstanceID value is not a safe indicator for whether or not the object is persistent.
I think it's not an issue in a build, but I could be wrong
From what I understand - if you save it to an asset, it will stay at negative instance ID until you reopen unity
Yes, I see the negative value for a preloaded gameobject in the scene while it is a prefab asset.
Just checking, is this more performant?
https://paste.ofcode.org/CvygbSJanas3EiWB6P8BpJ
Game runs smoothly on 60fps it's just the scrolling that's choppy
than what?
I don't think those scopes are doing anything btw
than previous, I guess my question was more does this look alright?
doesn't have to be perfect, just trying to avoid bad
seems fine...I think you may be outgrowing tags entirely here though
Not sure if I should ask this question here or in #archived-game-design BUT.
I'm trying to figure out the best approach to getting this to work:
The setup looks like this:
Both physical screens are actually one mesh where both screens share a single UV map.
What's currently displayed on the screens is done by using a single material with a render texture that is supplied with a second camera.
Every element is made with uGUI.
During playtime, there is a CinemachineVirtualCamera that is set to hard look at a game object I call "camera target."
What I want:
- I want to add a "cursor" to the monitors, it would function how a normal desktop cursor would.
- I need the cursor to actually be functional and actually "click" on UI elements.
Where I'm lost:
I'm not sure what approach would be best.
I've considered casting Physics Ray onto the screen, then figuring out where on the UV map that ray hits, but I'm not sure where to go from there. I'm sure I could figure out how to get the mouse to move, but I'm not sure how I would go about getting mouse clicks. Any suggestions?
Raycast -> UV Map Coords -> Canvas Coords -> ?
Could you point me to some alternatives?
well i'm actually not really sure what this code is doing
Fair
I would recommend a custom raycaster
that does the translation you described (raycast to hit point to uv coordinate)
as oppsed to using RaycastHit.textureCoord? any benefits?
I am making a โparameterizedโ hallway. Basically a cube of planes facing inward where the player is positioned inside.
I have a hallway object (script is attached to) that is the parent of all the cube faces(planes)
There are three variables: length, width and height. The cube scales to those values growing from the back edge.
The tags are to identify which face is which so they can be positioned properly.
-# Iโd send more code / a pic of the hierarchy but I donโt have my computer atm
that works if available. It's only available on MeshCollider
thats what I'm usin
so each plane has a tag?
Yes
sorry, I don't mean to sound rude or anything, I know I left out a ton in my description of my scene. There's just a lot
You could use a component like this:
public enum HallwayPart {
LeftWall,
RightWall,
Ceiling,
Floor
}
public class HallwayPlane : MonoBehaviour {
public HallwayPart Part;
}```
Then your other code can look at that instead of the tag
So classes over tags for id
You could even do something like this:
[Serializable]
public struct PartParams {
public Vector3 scale;
public Vector3 position;
}
public class HallwayPlane : MonoBehaviour {
public PartParams Params;
}```
And just - set this all up in the inspector
somethingf like that
this is a rough idea that needs to be hammered into something generally useful
For sure, I understand what you are getting at, Iโll definitely implement it when I get back on later today
Last question about the hallway for a bit, but when it comes to adding textures to the walls, especially for greater lengths; will textures tile across it properly automatically?
not specifically a coding question per se, but for some reason Unity is not wanting to recompile my scripts? I have to keep entering play mode or restarting Unity to make it recompile. I have auto-refresh enabled.
Only if you use a triplanar shader, or manually adjust the material scale
for example, I add a new public field. It won't appear in the inspector until I enter play mode/restart unity.
Another example, I comment out all the gizmo code. The gizmos still show until I enter play mode/restart unity.
I hate to ask the obvious questions but have you made sure you have no compile time errors?
no. If I did, I couldn't enter play mode. Or at the very least, I wouldn't be able to see changes that I made after entering play mode/restarting unity.
point
Domain reload is off on the project, but I have no control over that (i'm pretty sure it's a project-wide setting, right?). But I don't think that would cause any issues like this. Doesn't cause any issues for anyone else at work. I'm only asking here because they don't have any clue as to what's happening lol
it's really weird, because looking at the script file I can see my changes in the preview. But looking at the inspector, I don't see my changes until I hit play (which causes it to be recompiled)
Is Unity's built-in state machine editor only relevant to animations? Every time I've seen FSM visualized in a graph in a tutorial, it's regarding animations, and in every tutorial dealing with game physics, it seems that people are using text to program the state machine - what's with the discrepancy?
The animator uses a state machine and has a nice visual editor
that's the only thing of that nature built into Unity afaik
that's the only thing of that nature
anyone had the editor hang with this particular message? 6.18f1
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Mesh.MeshData.GetVertices.html
does this create a copy? im trying to avoid making a copy as i just need a readonly of the mesh verts
does it make a copy of what?
the vertices...
sorry i havent a clue, you can look through this discussions page though
https://discussions.unity.com/t/reading-mesh-data-without-unity-making-a-copy/123045/2
Vector3 is a value type. It can only be copied
i meant the buffer not the individual vertex
in other words i would much rather a pointer to the array not create a duplicate array
since im only using it for reading not editing
You pass in the array to use, so if you keep a reference to the array around it'll re-populate that one instead of making a new one
That method will copy the data. This is because the raw mesh data is not usually just an array of Vector3. There are UVs, normals, tangents, etc. all stored in the mesh buffer. You can access this buffer directly without copy with GetVertexData.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Mesh.MeshData.GetVertexData.html
To know what part of the array is position data, you have to query its layout with the methods in MeshData.
If it's about code, you would simply !ask your question here else you would do so in #๐ปโunity-talk
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
can i not use update in a script that derives form monobehaviour + something else?
usually my ide would finish this for me but its not giving me the option for this script
C# only allows one parent class
if you have any "something else"s, those would be interfaces
you can always have Update in a MonoBehaviour
make sure you don't already have one in this class for example
i have monobehaviour and ipointerdownhandler, and no existing update function, but its not letting me add update
yes sorry for the confusion
you can always type Update
My guess here is you have forgotten the opening bracket or something
given that the suggestions are interfaces
{}
when i do, its colored as normal Update would
no its below the start function so that impossible
show your full screen
sorry what else should i include?
the full screen lol, but it seems fine so don't worry about it
but any ideas on why my ide inst working for this script?
it doesnt give me the option for anything else either
showing the full screen might help - perhaps it's in a different assembly or something
it works for other scripts?
restart VS
i restarted and it doesnt fill anything...
wait now it works...
i tried typing fixed update and it started working again
im so confused
I am using Scriptable Objects to handle a Wave System in my game. Each Wave Object is comprised with at least 2-4 raids. In which my WaveManager will run in the game. This system works really well, but I am going into level production and now notice something big. I need at least 28 waves per level, or more, and this seems like I will not be able to manage them. I am probably going to make something around 20-50 levels, so this could be a very hefty amount of wave SO's I need to create. Just want to know a few things:
- Will the amount of SO's I will have result in big Memory sizes?
- How should I go about managing a big amount of SO's?
- Is this a bad idea?
something programmatic might be easier to manage
or a system where you can use a spreadsheet or something
indeed, what data changes that requires so many unique SO's?
consider even compacting the data into AnimationCurves or something
You are right. I'll just compact the data. Thank you
One other point, I doubt Memory will be a problem but having so many SO's may well affect the load time of your game as a lot of deserialization will be happening and there is no simple way to make that happen asynchronously
can anyone suggest me any asset or method to see memory usage in runtime for android build?
use the memory profiler: https://docs.unity3d.com/Packages/com.unity.memoryprofiler@1.1/manual/index.html
(yes you can use it with a build)
on screen? i meant any asset or method to show the usage on the mobiles's screen
i mean i am getting untracked heap of memory usage in memory profiler without any reason while using addressables, someone told me sometimes using memory profiler screenshot, untracked memory can increase, so i decided to test in other way
So im having the weirdest issue rn
I made code that handles a button press to swap to a different action map (new input system) and from that map hitting the same button it should swap back. That isnt whats happening though:
it goes from a-> b, but then trying to leave b will result in b -> a -> b.
I feel like currently when it switches maps the new one already listens to the same input press that triggered it to become active in the first place but i cant imagine that case resulting in such consistent behaviour....
let me post code
that is exactly the case. serious bug in the input system
ah I see. how would I work around that?
wait one, let me find the code
sure
Are you disabling the previous map?
Or we just wait for Steve, he might have the solution to the bug already
sure
Ok, so this is what I do when I change the map
public void OnConfig()
{
StartCoroutine(Config());
}
IEnumerator Config()
{
// Fix up for InputAction bug
int i = 0;
while (i < 40)
{
yield return null;
i++;
}
//yield return new WaitForSeconds(0.5f);
GameManager.instance.playerActions.OnDisable();
//SceneManager.LoadScene("GamePad");
Off();
input.SetActive(true);
}
basically build in a 40 frame delay so that the previous keypress disappears before changing the map
thats wild
as you can see I played with different options
i just tried a fix and it might not be the issue after all: when i set for the map switch to happen on button RELEASE instead of press, the behavriour works as intended except that it doesnt respond the very first time the button is pressed. after that, it works perfectly every time
well
you might need to play with the magic number, this was only tested on Windows
i suppose that might be a different issue altogether
I wonder if there is an option to invalidate the latest input events before disabling the whole system and start a new one
This is a problem I encoundered when I had actions on started and performed
not that I found
thats what i was thinking to manualyl create, in the new map turn on some bool that suppresses listens until the key is released
my testing shows that even if you disable the map and remove all of the events you still get this 40 frame holdover for the last key pressed
thats so odd
does the yield return loop loop exactly once every frame?
i assume so
I am more like wondering if you can replace that "magic number" with something coming from the system as callback
yes
pretty sure I played with a range of numbers and 40 was the one that guaranteed that the previous keypress was gone
Letting this event reset a bool until no more input is coming in for the next frame?
Or maybe you can store the input itself or its id and compare against it or it being null before activating the new map
I'll leave it with you to play with, if you find a better way please let me know
@short osprey keep us on track. I dont have time for testing right now sadly ๐
Also, maybe move to #๐ฑ๏ธโinput-system ๐
same
working on it
as a rough guide the 40 frames was my game running at 200FPS so about 0.2 seconds in real time
i cant really figure out how to navigate this event, it doesnt seem to act how i expect
What do you mean exactly?
I was expecting to be able to access a "stack trace" so to speak of all previously read inputs that are queud and somehow make one be ignored
but i cnt seem to find out how to achieve this
How do you register to the current map? Are you using events like .performed?
controls.Movement.GravityMenu.started += SignalGravityMenu;
GameStateManager.Instance.CurrentStateChanged += HandleStateChange;
//Further on
//This code is ran whenever the GameStateManager.CurrentState is changed
void HandleStateChange(GameStateChangedContext context)
{
switch (context.NewState)
{
case GameState.GravityMenu:
controls.Movement.Disable();
break;
case GameState.Playing:
controls.Movement.Enable();
break;
}
}
The above code is in the regular movement script. the script for navigating the 'gravity menu' has equivalent methods but mirrored
...alternativelty i could make leaving the menu a different button to circumvent the issue altogether
but i dont like that
I'm in a very early stage of development and encounterd a weird issue. When my character turns to the left with the script below it start really lagging. I can debug the fps and it shows steady ~300 fps and nothing major comes up in the profiler. It still looks like its dropping from 300 to around 30. If I disable the Look component it works fine again.
I was chaning X scale earlier to "rotate" the character, but added scale animations and decided to change the rotation instead.
Do you know what might be happening?
using UnityEngine;
public class Look : Capability
{
protected override void Update()
{
base.Update();
RegisterInput();
}
private void RegisterInput()
{
if (IsLocked)
return;
if (_controller.RetrieveMoveInput().x < 0) SetYRot(180);
if (_controller.RetrieveMoveInput().x > 0) SetYRot(0);
}
private void SetYRot(float YRot) => transform.rotation = Quaternion.Euler(0, YRot, 0);
}
i made a pretty simple path finding algorithm for my enemies and this one works with a visibility graph. here every Node knows which Nodes its connected to and which Nodes are visible where connections are the only thing that will block visibility. this works fine for the most part, but when you have for example 4 nodes arranged in a square with 4 more arranged in a square inside of it, the corners of the smaller square will think it can see the opposite corner of the smaller square, even though the visibility line is going outside of the polygon. any way i could fix this?
Unless that base class or those retrieve input methods are doing something weird, theres no way this causes lag. Maybe it's just stuttering around instead
I'm sure its the SetYRot method causing the issue. If I leave it blank the stutter is gone
private void SetYRot(float YRot) { }
Your issue sounds like camera stutter, not performance related
Well yes, if you no longer rotate the object itll stop rotating..
You should probably show the algorithm you're talking about. It's hard to visualize what exactly the issue is, or what the intended result is.
I have a video of the left turn lags, but it barly noticable since the framerate of the video is much lower then in editor to begin with
I disabled the cinemachine brain on the camera, but with no result
the camera is also anchored so I dont see why Y rotation would cause an issue
Change the 'Update' method used on the cinemachine brain
I don't see any lag in that video
I disabled the CM brain entirely
Yes, like I said its hard to capture on video because of the framerate
Fair enough, i'll come back on it in a few hours
what is the best approach for isometric sorting in unity?
Whats your issue with it? Isometric could be just a camera setup and still be 3D
it's in 2d, I'm trying to think of a way to properly render the player in front/behind a long diagonal sprite. One way I thought of was finding closest point for the collider, and then checking if a specific point for the player is above/below that point in the collider. Not sure about the efficiency of this though, especially when hundreds of objects might be in the scene
And I would also need to render it for multiple controllable characters
for some reason continuously setting the rotation caused the character to stutter (not the camera, or the framerate). Adding a simple check fixed the issue:
private void SetYRot(float yRot)
{
if (transform.eulerAngles.y == yRot)
return;
transform.rotation = Quaternion.Euler(0, yRot, 0);
}
you really should not do this
if (transform.eulerAngles.y == yRot)
firstly the read value of .y is probably not what you are expecting
secondly never check float values for equality
whats the implementation of SetYRot
it's a good point with the comprision, but there are no calculations on the rotation. I'm only setting it to 0 or 180 in one script and I think it's unlikely going to cause precision issues
the whole script is above
i just saw
just be careful, it may work under certain circumstances but it most definitely will not work under all circumstances
just because that is what you are setting it do does not mean that those are the only possible numbers you'll get out of it. eulerAngles are interpreted from the quaternion at the time you access them and because there are a large number of ways that a rotation can be expressed in degrees, you may be comparing against a number you didn't expect. and of course you have no control over whether a floating point number is imprecise.
I will keep that in mind, thanks
Anyone able to help me out?
I'm trying to create a reload for my gun, I shoot it ten times, reload it and then my animations don't work.
Im pretty new to coding but Im familiar with how Unity's systems work
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
I have a struct in my script called criminals and i have a list of these structs, in my inspector i have all my criteria and stuff filled out, the struct looks like:
[System.Serializable]
public class Criminal
{
public string name;
public bool male;
public bool guns;
public bool melee;
}
each of the criminals are different, how do i get a list that changes depending on what criteria you know the criminals have?
Not sure what you mean by " a list that changes depending on what criteria you know the criminals have"
What do you mean by "criteria", first of all.
So criteria would be whether the criminal is male, uses guns, uses melee weapons. Say i have Ben, Jim, and Katherine. Ben and Jim are males, so if in the evidence i tick "male" only Ben and Jim show in the list, and then if Ben and Katherine use guns and the I tick "guns" those two show in the list, but if i pick, "male" and "guns" only ben pops up
Does that make more sense?
Like in phasmophobia but with lists
sounds like a job for LinQ
Sounds like you want to build a database to do searches
You could literally use SQLLite or something
This is one option
It kind of depends how much data we're talking about here
If it's just less than 200 or so items, you can probably get away with just a list and Linq
It is less than 200 but I'm not sure how to do it with Linq.
I mean it's exactly what Linq was made for
Use Where to filter the list for each criteria you select
IEnumerable<Person> filteredCollection =
listOfAllPeople
.Where(p => p.Gender == "Male")
.Where(p => p.Weapon == "Gun")
.OrderBy((p1, p2) => p1.Name.CompareTo(p2.Name));
In this case:
Where(p => p.male)```
But an enum field for the weapon type would definitely be better than multiple bools unless there's only two options
didnt see that
Unity has this pattern of returning value or null. GetComponent<...>() or FindAction allows me to write:
InputAction x = ia.FindAction("something");
if (x != null) ....
How can I write my own function that returns a type (InputAction) or null?
InputAction MyFunction()
{
InputAction x;
// ...
if(someCondition)
{
return x;
}
else
{
return null;
}
}
Note this only works for reference types
if the type you want to return is a value type, null is not a valid value
in those cases, it's best to use the Try/Get pattern.
Soo I acutally don't know where to post this but this channel here seems to be the best.
I created a "Chat UI" (very very basic) with UI Toolkit and integrated it sucessfully. Issue right now is when I'm in the text input field and start typing my character starts moving too. I tried different ways now via Callbacks (FocusIn, FocusOut) to disable the character script when I'm in the input field and this works fine - but whenever the window as a whole is open and I move my character the input field gets instantly focused and the character script stops.
Tried it with disabling the focusable property when FocusOut Callback is called but now I can't access the field anymore...
Someone got a tip on how to fix this? Spend hours on that now and can't move forward...
Code of last attempt:
_messageInput.RegisterCallback<FocusInEvent>(evt =>
{
_root.BringToFront();
_messageInput.focusable = true;
GameObject.Find("Player(Clone)").GetComponent<PlayerController>().enabled = false;
});
_messageInput.RegisterCallback<FocusOutEvent>(evt =>
{
_root.SendToBack();
_messageInput.focusable = false;
GameObject.Find("Player(Clone)").GetComponent<PlayerController>().enabled = true;
});
Is there any help on how to have a local like "arms only" model with animations, but have the networked players have a full body with different animations ?
i cant really find ANY help on this topic no matter how hard i google or youtube, i only find unrelevant stuff
Multiplayer stuff, specifically FishNet, but a Tutorial for another Framework works too
So you open the chat and it autofocuses the text bar, i am not sure how its in uitk but in the normal unity stuff you can set a tab order, set the auto focus to a different, maybe fake object on open
Hi i am pretty new to coding
i found a free behaviour tree
but have no idea how to use it
And?
so learn it lol
if you're new to coding you should probably not be working on Behavior trees just yet anyway.
Probably sounds dumb now but I was apparently thinking completely wrong.
My original approach was to manage all that inside the chat window script but after I thought a little bit more that doesn't makes sense when working with multiple player prefabs (multiplayer).
Refactored that whole thing now to use internal variables which I access from my player controller and then block movement from there - works fine now 
Specific questions can be answered but we don't really have anything to go off of. What the problem is, what the asset even is, what you need help with, etc.
but i need to make a boss , and my animator controller looks like shit
I need to learn it ig
ya go do that lol
yeah sorry
Hi guys.
I'm using Zenject in Unity and everything works fine in the editor, however, when I built the game, Zenject is not injecting into "loading object", thus I cannot load the game. Am I supposed to do something specific when building the game?
THis code worked perfectly fine before but now it all of a sudden creates this error
cannot remove from blockades inside the foreach
You cannot modify a list you are iterating over. At no point would this have worked
I swear to god it was working, i have a working version of this on github, but maybe its adifferent part thats causing the actuall issues i have and not htis error
thank you
no way, make it a reverse for loop instead of the foreach
ill try that thanks
maybe this error was there but the actuall gameplay part was working but its broken now and this is the only error I could find
it's definitely an error, reverse for will fix it
When I call this coroutine to activate a very simple UI element, the game freezes for a split second. I checked and It does not get called multiple times, and it only happens with a UI element, I know Unity redraws the canvas each time you change something, but it's not the explanation because if I activate the UI element without the coroutine, there's no spike in the profiler.
Now the error is gone but the logic of my game is even more broken TT
why would it be broken? Show latest code
Hi, im having an issue with my item system where when the player picks up the item whilst moving, the item will be offset to the last position of the players hand transform, im assuming i can probably update the position somewhere but im not sure how.
its too much code, its about 900 lines of spaghetti code from a game jam game that im trying to clean up and fix
just show what you changed
odd way to do a reverse for, normally you would do Count-1
blockades.RemoveAt(t-1)
@rocky jackal
that ain't a reverse for
the for loop is working you dont need to fix that its the other logic in my game that broken
Huh? It results in this
well, your remove is a little dodgy, use RemoveAt
ok
sorry, I thought you were showing a reverse for
Was just showing how to convert from foreach > for > reverse for
is there a cleaner way of doing this?
private char GetModifiersKey(IKeyboardEvent eventInfo)
{
var isShiftActive = eventInfo.modifiers is EventModifiers.Shift;
bool isCapsActive = _isCapsActive || isShiftActive;
char key = (char)eventInfo.keyCode;
if (!isCapsActive)
return key;
char mappedKey = GetMappedKey(key);
if (mappedKey != key)
return mappedKey;
return char.IsLower(key) ? char.ToUpper(key) : char.ToLower(key);
}
private char GetMappedKey(char key)
{
return key switch
{
'`' => '~',
'1' => '!',
'2' => '@',
'3' => '#',
'4' => '$',
'5' => '%',
'6' => '^',
'7' => '&',
'8' => '*',
'9' => '(',
'0' => ')',
'-' => '_',
'=' => '+',
'[' => '{',
']' => '}',
'\\' => '|',
';' => ':',
'\'' => '"',
',' => '<',
'.' => '>',
'/' => '?',
_ => key
};
}```
Use a damned array
array for?
both sides of your switch
modifierKeyArray[normalKeyArray.indexOf(key)]
then i have to iterate thru one of them
The switch is big enough (tested) to compile into a jump table, it'll probably be more efficient than using an array
well what do you think is happening in your switch?
what spr2 said
jump tables aren't magic, key still has to be evaluated
bump
Is playerHand a child of the player?
I don't use DOTween but I suppose you should use local instead of world. Replace your DoMove line with: cs transform.DOLocalMove(Vector3.zero, 0.4f);
This should make it move to a local zero position which would be equal to its parent's position (playerHand)
child of the camera which is a child of the player
ill try that
So I'm trying to use a TMP_InputField to try and emulate a computer console / terminal.
Issue is I'm trying to do something like this:
user@localhost: (text input goes here)
Where that beginning part is bold, and the input text isn't.
I figured I could try to use rich text, but then I'd have the issue with the user being able to insert their own rich text tags.
If i try to limit what the user can type with the custom content type dropdown, then I can't add tags at all.
I'm, wondering if I'm going to have to code my own solution here, or if anyone knows something I don't.
And I should add that I tried setting "rich text" to true, and "allow rich text editing" to false in the Input Field component, but that still didn't work.
Surely the first part should be a separate text element
are you absolutely sure that is what it says?
its a 2d project
i just added a navmesh , installed the AI packages
and it shows this
yes, navmesh does not work in 2D
Yeah thats what I wanted to do initally, but then when the second part has to wrap to the next line, its indentation is wrong. (Technically the behaviour does exactly what its supposed to do, its just not inline with the first part, which is what i need.)
I think i figured it out hopefully though. My issue was that I was trying to enable the rich text field in the TMP_Text component, and not the TMP_InputField.
As for if the user will be able to add their own tags, idk yet, but at this point, I'll just code my own solution for that if it comes to it.
You can set the line-indent so that the first line is not under the prompt text
If the prompt is in the input field the player can edit it
Someone said I should keep floats and bools in the same line instead of making a new line for each, so I did that. But i don't know if I can do the same for transforms, audio clips, audio sources, ints, game objects, TMP Text, ect.
You mean the variable definitions?
Sounds like a bad idea in general
unless they're very closely related
like int x, y, z; or something
otherwise - best to keep each variable declaration separate
i absolutely agree with praetor's suggestion. i do just want to point out that it is possible for any type
Another thing they said to me is use [SerializeField] more, because just using public makes the script use more power. Like this:
[SerializeField] private float waitTime, activeTime;
https://github.com/h8man/NavMeshPlus adds 2D support.
using "more power" is inaccurate. however it is better to make things private and use that attribute rather than just making everything public. It's more about encapsulation though, you don't need every variable accessible to other objects, the only things that should be public are things that absolutely must be accessed by other objects.
Yea, that's what I did to one of the floats I found
so I kept that one stayed just public
Another thing, this one my friend told me; Is that I should use (other.CompareTag("Player")) instead of if (other.transform.tag == "Player")
yes, CompareTag has a couple of benefits, it is slightly faster than comparing the strings with the equality operator, but more importantly it will throw an exception when a tag you pass to it does not exist (such as if you spelled it wrong) instead of just returning false
is there a way to get pixel perfect camera to work with custom meshes on a meshrenderer in 2d?
How can I use SceneManager.CreateScene to load into a new empty scene
Seems pretty useless to be able to create a scene and not use it
the scene it creates is loaded additively immediately upon creation. so just unload your other scene(s)
Wait really? Damn
yes, did you not read the documentation or even test it?
Oh right I missed the open instantly bit
So once it's open I cant do anything else?
I guess if I want to reopen it I have to dispose of it. It's a disposable scene anyways
What do you mean do anything else? What else are you expecting to do with it
Unload it and load it
Why not just create a scene asset and reference that? Especially if you're trying to have some default objects in it
I want to make this really easy to use for a non-programmer, any way i can add comments to explain what these do in the editor?
either use the Tooltip attribute to add comments when someone hovers over the name or write a custom inspector, property drawer for your own attribute that draws the text, or an asset like NaughtyAttributes or Odin Inspector which i believe both have attributes that do that
As in guns and then melee are in an enum together?
two mutually exclusive bools are never the answer
either use one bool, isMelee, and you know if it's false that it's obviously ranged
I'm doing it so it can be both guns and melee though
Or use an enum if there's more than one option:
enum WeaponType {
Melee,
Ranged,
Whip,
Rocket
}
ah - if they're aren't mutually exclusive, that makes more sense at least.
Then that's fine
Enum still may be a better option here though as it can potentially cover multiple cases
I might try out an enum, i'll let you know how it goes
You can specifically use flag enums for these
[System.Flags]
public enum weaponry {
Guns = 0,
Melee = 1
}
Like this?
[System.Flags]
public enum Weaponry
{
Gun = 1 << 0,
Melee = 1 << 1
}
use powers of 2 for flags and you can safely have multiple flags per object
more like this
the idea is each valid type is given a positive (not 0!) value that's a power of 2
so you can check if something is a gun with (value & Weaponry.Gun) != 0, and if something is either a gun or melee with (value & (Weaponry.Gun | Weaponry.Melee)) != 0
also, checking if something is both gun and melee with (value & (Weaponry.Gun | Weaponry.Melee)) == (Weaponry.Gun | Weaponry.Melee)
I also want the player to be able to cross it out, how would i put that in the flag enum?
Wdym cross it out?
So like you have: unknown, have it, or don't have it.
I'd probably use a separate variable for that, although I'm not entirely in the loop when it comes to this conversation