#archived-code-general
1 messages Β· Page 96 of 1
the other side inverted, as it should
Sometimes, z axis of pos gives me neg value, but I look at the indicator (it's in my camera view) and vice versa:
Code:
var pos = renderer.GetRectTransform().InverseTransformPoint(renderer.camera.WorldToScreenPoint(indicator.transform.position));
What's the problem?
That's something you need to tell us. What's happening that shouldn't be happening. What's not happening that should be happening? What're you trying to do? We can read the code fine. We can assume your underlying intentions but that isn't something we're wanting or should be needing to do. Just tell us what the problem is.
hi, I can xpost this to #π²βui-ux but I'm having an issue where a button is staying highlighted after it's clicked because it disables its parent object as a result of the click. Is there a way to "force" its state back to normal?
This is the general coding channel. Is it related to code?
I was hoping to set its state back to normal through code yes
I wasn't able to find anything in the documentation about setting a button's state
Sounds like something you should ask in #π²βui-ux or #π»βunity-talk as you're unaware of what you're needing to do to solve your problem.
Well, my problem is gone when I change order of execution. I used for updating indicators to the FixedUpdate and everything is good.
I know that FixedUpdate is for the physics calculations, but it solved the issue.
So!
Oh well. Simply going to inform you that you never stated a problem to begin with.
is it really necessary to be this passive aggressive when people are asking for help?
If you need to move your code to FixedUpdate for it to work, you're doing something very wrong
Example: "When I press jump my character jumps 10 units. The inspector shows this to be true. Here's some code. What's the problem?"
It isn't very useful.
I do update of camera in LateUpdate.
That's fine
I did update of indicator in Update.
I usually get straight to the point to avoid unnecessary probing.
But I had this problem.
You should only do that for physics calculations
Well I don't know what the problem is, do I?
Anyway, it fixed it I dunno this magic.
I use code from the HUD indicator asset.
I cringe when people say they used code, I hope you know what it does π€
I needed fast solution for this.
And it solved the task ideally.
But was that strange behaviour.
Used code is not the cringe, it's reusability.
Yeah that's one way of saying it
Until you run into errors, and you are forced to copy paste your code into FixedUpdate for it to work
But hey, as long as it works right?
I suppose compromises must be made when you copy paste other people's code and you're not sure how to fix it
And this is exactly this scenario in my case.
i used this function but when the bullet hits the player with the tag, it doesnt destory the bullet
are you sure this scope works? you can check by using debug.log or take a look at players health if the took any damage then its working
Log the tag of other cs Debug.Log($"{other.name} has a tag of {other.tag}", other.gameObject);before the if statement and possibly with collapsed logs so that the console doesn't spam with repeats.
i think so
ill do that in a second
be sure of it by logging or looking at players health
if i instantiate a particle prefab when i collide with something, how should i be destroying the particle after its particle cycle has finished
because rn it just kinda sits inside the inspector as an instantiated object
unity wont let me just called Destroy on it
Care to share the code?
yes one moment
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletProjectile : MonoBehaviour
{
private Rigidbody br;
[SerializeField]
private Transform hitBullet;
private void Awake()
{
br = GetComponent<Rigidbody>();
}
private void Start()
{
float speed = 40f;
br.velocity = transform.forward * speed;
}
private void OnTriggerEnter(Collider other)
{
if (other.GetComponent<BulletTarget>() != null)
{
Instantiate(hitBullet, transform.position, Quaternion.identity);
// Destroy(other.gameObject);
}
Destroy(gameObject);
}
}
Theres a setting that lets the particlesystem auto destruct after its done
https://docs.unity3d.com/ScriptReference/ParticleSystem.MainModule-stopAction.html
It's probably getting called twice then. If the other object has 2 colliders, OnTriggerEnter will run for each collider
ah yes
Modifying Script Execution Order only impacts order for the same functions, right? Meaning if a -1 priority an 0 priority scripts are in a same scene, they will execute Awake() -1 first then 0, and only then, they will execute OnEnable() if enabled? In my case I have a Script triggering OnEnable() before my other script has triggered its Awake()
i do have 2 colliders 1 is for a trigger and 1 collider
some reason they were both checked as istrigger
guys i'm really struggling with something, i'm making an idle game in the style of cookie clicker but i'm really struggling how to handle the larger number, and how to display them as like "thousand" and "million" without hard coding it and incrementing the number into a new variable each time. anyone know how to do that?
Not sure if this is the solution your looking for, but try looking at the buttonβs βselectedβ color, maybe try setting it to the normal color. Also you could just manually set the color in script (if the only thing that changes is the color, which by default I think it is).
thank you
Hi, I'm calling this function in my Update()
private void SaveSamplesToFile()
{
if (gestureSamples.Count == 0)
{
return;
}
string directory = EditorUtility.SaveFilePanelInProject("Select File to Save Data", "NewSample01.json", ".json", "Please enter the file name to which the sample will be saved.", defaultSaveFilePath);
if (directory.Length == 0)
{
// User cancelled the selection, do nothing.
return;
}
string json = JsonUtility.ToJson(gestureSamples);
File.Create(directory).Dispose();
File.WriteAllText(directory, json);
Debug.Log("File saved to " + directory);
}
unfortunately, I can only close the window that pops up, I can't actually select any file to save. Does anyone know what's happening? The docs are useless here
nevermind, not useless. "json" not ".json", my bad
I have a game with a primitive code editor that allows dragging and dropping commands into pre-existing slots in a "program" that users can run.
I'd like to rework this so users can drag commands into an editor area and drop them above or below other blocks (they then snap together).
Right now I'm considering having a "line of code" prefab that's created whenever necessary, with a snapping slot (I've already built) for each line.
However, I really don't think instantiating and destroying prefabs that often would work out well.
All boiled down: What is your suggestion for how a stack of vertical gameobjects can be rearranged, inserted, removed etc. in a way that won't impact performance terribly?
Check if your player has the "Player" tag.
Also, where did you put the Debug.Log?
Why does my Entities package not include TransformAspect cs? Using 2022.2 and 1.0 dots
Pretty sure this won't result in valid JSON. Looks like gestureSamples is an array, and JSONUtility does not like that
It's a list, but good to know
what would you recommend instead?
Well JSONUtility is a very shit tool
There should be a NewtonSoft.JSON Unity package
Otherwise you can download the Newtonsoft.JSON DLL manually (Just make sure you take the .NET Standard 2.0 version), and place it in a plugins/ folder.
JsonUtility gives me an empty file, but the newtonsoft version gives me a self referencing loop error for property "normalized" with type Unityengine.Vector3 :/
that's why I tried switching to JsonUtility in the first place
I tried sth like this
string json = JsonConvert.SerializeObject(gestureSamples, Formatting.Indented);
Then you should probably map your list into an anonymous object when you serialize it. I'm not sure why that can even happen with a Vector3
var anonObject = gestureSamples.Select(x => return new {
field1 = x.field1;
problematicField = new { x = problematicField.x, y = problematicField.y, z = problematicField.z }
});
I didn't expect this would even be required, but here it is
Has anyone ever had the system call/load a 3d model from url into Unity at runtime?
so a project that has become apk can call a 3d model from the url (loaded from the internet)
I want to create such a vr presentation by calling the 3d object from url
someone help me to make a character jump because in my code when it jumps it doesn't come back down
if(input.getkeydown(jump))
{
rb.AddForce(Vector3.up * thrust, ForceMode.Impulse);
}
done
you need to look at addressables and asset bundles
but I have to create some variable?
do you?
I want to convert the game to an apk file, but I'm getting an error like this, how can I solve it?
that is a warning not an error. Note Yellow triangle not Red Circle
does not create the apk file
First thing to try is close your project and open it again. Then try to build
I deleted and reinstalled Unity but I still get the same error.
Edit->Preferences->External Tools
Screenshot the window
Also which Unity version?
Is there a way for a prefab to not serialize one of its fields, but retain the scene's serialized value?
no, a prefab can have no connection to a scene
Yeah that was unclear, apologies, let me try that again
Hello, if i make a thread with a while loop inside, will it take alot of performance?
In trying to make a thread that listen to editor camera's movement and other stuff like check if any object moved in editor mode.
But idk if using a while loop in a thread will take alot of performance or not. If it does, is there anyway else i could reduce the performance?
Unity version LTS but I have a little job done, I'll post the part you want shortly.
which LTS? There are lots of different ones
If I drag a prefab in the scene at editor time, and I modify one of its fields, I'd be able to hit apply to modify the prefab. What I'm trying to do is mark certain fields to avoid having them be part of the prefab's serialization process. The idea is to be able to do per-scene tweaks without risking overriding the values in other instances scattered across the game.
you would need a custom editor for the script but, yes, it is doable
Okay, thank you
Guys, what strategy can I use to change meshs and materials at runtime? My scenario is this: I have a Corruption Index, and each index (0%, 20%, ..., 100%), I need change my mesh and materials to a different. What approach can I use? Any existing feature at Unity can help me or I need build the in entire logic to do that?
@knotty sun sorry for the ping, but do u know any solution about this? If u do, please tell me
Thanks alot =)
you need to build the logic
Firstly: NEVER ping someone randomly. Just for that I might not answer you!
But..
You do realise that most Unity API's do not work outside of the main thread so multi threading might not work for you at all
Also, no, a while in a thread will not take any more performance than a while in the main thread, you will just not notice the FPS drop as much
Ooh, sorry for the ping! Wouldn't do that again
Do you guys know a way to know why a GameObject is destroyed? I have OnDestroyed getting called immediately when I start play mode, tried printing StackTrace in OnDestroyed() and OnDisable() but nothing
maybe use breakpoint in OnDestroy and check the call stack
Call stack is empty before ondestroy call :/
is this a singleton..?
does it have code in it that destroys itself if there are multiple of it?
it is a singleton, used to have the destroy if already existing, I removed it but still same result
i'd Find All Destroy calls in the project then
yes, checked it also, no other reference to this object in a destroy call, It looks like it is destroyed from unity itself, like when we change a scene
you commented out the Destroy in the singleton part of this?
yes
not sure then
one weird thing I just realised, when getting through Awake() for the first time, the instance already has a value no my bad it doesnt
Ok, found it, I just didn't add it to my don't destroy onload list π€¦ββοΈ
Unity 2021.3.24f1
that looks fine.
Have you checked the Editor Log file for more information?
How would you make text run across the screen like this? I managed it in Python before but Unity is different haha
https://www.youtube.com/watch?v=zMeMe_8X-tU
09:56 (Picked a random VN I don't play this game irl)
Subscribe For more Gameplay
Anime Watch For free : http://bit.ly/1sqeHwi
Subscribe For more : http://bit.ly/1trFTbp
Follow Me On Facebook : http://on.fb.me/1l49IK1
Follow Me On Twitter : http://bit.ly/1o3k7pp
youtube/google Typing effect Unity
usually it's a coroutine looping through char array aka string
thanks
Hi guys, any idea how I can rotate my character (Kinematic RB) with a rotating/moving platform it's standing on?
Thought about checking if platform has a rigidbody and applying its velocity to my character, but not sure if there is a better way (or this would work at all π )
Whenever i add anything to do with normals in shader code (o.Normal = IN.worldNormal), my material turns full black. Any idea why?
look how the kinematic controller does it
take notes
You mean this one? => https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
yea
they got moving platforms
Nice, will have a look, thanks!
while (true)
{
randPos = new(Random.Range(-rangeX, rangeX), Random.Range(-rangeY, rangeY));
Collider2D collider = Physics2D.OverlapCircle(randPos, _radius);
if(collider == null)
{
CreateWell(randPos, _lavaBig, _lavaSmall);
break;
}
}
Hi, im trying to spread objects randomly on the Area without Collisions, but it always creates them in the Wrong places...
does anyone know a solution?
@viral prairie
wops wrong reply soz @opal cargo
wdym by "wrong places"
that is extremely vague
inside of other objects with colliders
You're not accounting for that in your code
the overlap check seems reasonable
ye
always a good idea to debug these Physics functions to visualize where it actually goes etc.
but in this case if you see it inside other objects then make sure colliders are appropriate sizes ?
I use usually a CheckBox or CheckSphere for these types of things tho
even if it is like 3 times to big, it still appears directly inside others
much easier to use boolean
im bound to 2d....
show the inspector for one of these obstacles
oh yeah, Physics2D lacks the Check functions
its the only one
yeah sadly OverlapCircle is the best in 2D
so I'm guessing collider is always null and not finding anything
are you adding tiles?
When you add or remove Tiles on the Tilemap component, the Tilemap Collider 2D updates the Collider shapes during LateUpdate. It batches multiple Tile changes together to ensure minimal impact on performance.
oh this is tilemap
you might need the World to Cell
function
physics raycast and tilemap are 2 Different coords
worldpos vs gridpos
arent these the same if Cellsize is 1?
Sadly, delay fixed the problem...
delay ?
Yes i create the Tile-Bulshit in awake, putting the distribution intostart didnt help...
oh.. I thought you had this in a coroutine
I have this if statement that's throwing a null reference exception, what could possible be null here without making one of the !=null false???? wait.. i dont think it could be null... but ill add a test for tilesInMRange to make sure
if (tInThreatRange != null && tile.Value != null && ally.OccupiedTile != null && tInThreatRange.Contains(tile.Value) && tile.Value != ally.OccupiedTile && !tilesInMRange.Contains(tile.Value))
wait it actually might be that lemme test
tile could be null
ally could be null
tilesInMRange could be bull
Lots of options
xD that's a big ass if &&
I figured it out, in this context ally and tile cant be null due to other stuff it was tilesInMRange
ive made an inventory fully from scratch with no tutorial what so ever, can i have some feedback on whats considered "good" and whats considered bad? so i know for in the future
it works in the ui and also works without any error so far
im not worrying, its just im new to unity and i dont know whats considered the standard haha
the standard are the usual things, try to stick to SOLID etc.
write clean legible code
i did this more over to test my skills i cant move on with my game if i have to go to a tutorial on anything i want to implement π
avoid repeating yourself ```cs
slotHolder.transform.GetChild(i).GetChild(0).GetComponent<Image>().sprite = null;
slotHolder.transform.GetChild(i).GetChild(0).GetComponent<Image>().enabled```
i was thinking about doing something for that but i didnt know what i should do for it
any suggestions?
use variables
how would i cache that? if you know what i mean
var slotlHolderImage = slotHolder.transform.GetChild(i).GetChild(0).GetComponent<Image>();
slotlHolderImage.sprite
slotlHolderImage .enabled
etc
that's mostly what's important
ya regions is good
so i can know what group the function belongs to
"avoid repeating yourself" was said to Selfrep
π
regions were a mistake
i never fold my code
ive also been trying not to populate the Update function with alot of code
rather just putting them in seperate functions and calling it from update
i've done that for one monstrous 2,500 line script
I generally avoid Update loop unless i have to
don't judge me too much
i rather use a coroutine as onetime thing
Senses() calls Sight(), Hearing(), and Touch()
i tried splitting the class into partial classes and it was just a nuisance
xDDD
i'm not sure what i'm gonna do about that
there's ~just~ enough coupling between different systems to make it non-trivial to split up
void RefreshUI()
{
// we loop over our slots
for (int i = 0; i < slots.Count; i++)
{
var slotHolderImage = slotHolder.transform
.GetChild(i)
.GetChild(0)
.GetComponent<Image>();
// set the image
if (slots[i].GetItem() != null)
{
// TODO: Incorperate Item Amount into this
slotHolderImage.sprite = slots[i].GetItem().ItemIcon;
slotHolderImage.enabled = true;
}
else
{
// get slotpanel -> get image from slot panel
slotHolderImage.sprite = null;
slotHolderImage.enabled = false;
}
}
}
unpopular : I've yet to find partial classes useful in unity
looks alot cleaner now
maybe it's just OK that my complex enemy AI script is complicated
nothing just use proper nav
there is search by methods, there are hotkeys to jump to the top bar with class/method nav
what i normally do is just collapse all of the other regions when im working on a specific region/s
i like cmd-shift-o in VSCode
it searches for symbols in the current file
cmd-t is the entire solution, and isn't as fast
of course, what i do in practice is start scrolling to find something
then i keep doing it because of the sunk cost fallacy
you use vs?
who doesnt use vs tbf
those who use rider
ngl never heard of it
vscode, not vs
yikes
VSCode gang
im now looking down on you both
π€ um actually you need a working debugger
i simply yell at my computer until it works
ignore the sprites π i couldnt find anything quick
i love grabbing random UI icons
π i had no onhand sprites to use so i just started searching from the ones i imported a little while ago π
more or less the biggest thing i get stuck on isnt the code its self (unless its decently complicated) its the logic behind the script
yeah that's the important stuff is logic not the actual code
I don't have a sprite for my main character yet, so for now it is just this cute penguin
lol
π
tbh that's why I laugh when someone says they memorize code
Memorizing and knowing how it works are 2 totally differnet things haha
just because u can write it doesnt mean u understand it
eg GPT
i watched a video earlier when i was trying to search up some tutorials on some stuff and it was about how watching tutorials will poisen your learning progress (ironic)
We've all used game dev tutorials in an attempt to learn how to become a game developer. They're such a valuable source of information... but are they?
Why Game Dev Tutorials Will Poison Your Progress
Game developers who share tutorials on how to make games are not evil. They have good intentions. The problem is that Game Development is not a...
this one
and it made me realize that what hes saying is actually very true so im trying to shift away from tutorials as much as possible
tbh I agree
I found myself doing so many errors at first because all the tutorials try to make it simple for new people but just makes new people learning bad ways of doing what they want xd
depends highly on the person as wel, generally you're just copy and pasting so yeah ppl don't understand what they're copying
but this can lead to further curiosities on how it actually works and do self-researching
Yeah for me i partially understood what was being made and tried to derive from it, but most of it i didnt understand
yup yup
tutorials are very useful if you already know how stuff works(mostly) and you just needed that idea to spark off the How but you can then mutate it to fit your needs
exactly
its an eye opener because when i scroll to comments alot of people will just post there errors there ask how to fix which in my eyes means they just copy and pasted it without knowing how it actually works
yes and or sometimes bad oversight from tutorial content creator
I hate tutorials that post with errors in code/logic without omitting those
I haven't released a vid unless I know there are no actual syntax errors, or any flaws like that. I just redo the whole video from scratch, not even edit
agreed however for me personally i just feel like im copying and pasting, i will watch some tutorials if i really need to but i will just listening to mostly the logic behind it haha
watch the tutorial like 3-4 times before jumping into the code itself, it will change how you view the tutorial usually
this is assuming it's a good tutorial
like Seb Lague or alike
some tutorials will just tell you what to do without explaining how it works
yeah skip those
the older unity ones are lokey hidden gems
this dude has good tuts
https://www.youtube.com/c/SebastianLague
for me its like i know how to do it sometimes its just idk if im doing it the right way, the way that wont cause bugs but however that is apart of learning ig
think ive watched a few of his videos tbf when browsing YT
does he do ML?
he might , haven't checked his stuff in a while
he has 1 video on ML in his playlist
there a few around that are decent too
most of them are devlogs
cause you know...hard work aint free lol
hello! does this ring any bells in how would i implement a functionality like this picture describes? (this is a pretty useless exercise that i am tasked with doing)
Yeah haha, tbf it might be worth me documenting my progress with devlogs on my game
Anyways i sleep for now
trigger colliders and OnTriggerEnter?
This is always returning with a count of 0 not sure why
public List<Tile> GetAllTilesInRange(Vector2Int pos, float maxrange, float minrange)
{
return tiles.Values.Where(t => Vector2.Distance(t.Pos, pos) <= maxrange-.5 && Vector2Int.Distance(t.Pos, pos) >= minrange+.5).ToList();
}
i tried this with a 3d collider that i "flattened" by putting y=0 and my game crashed
you can't flatten 3d colliders
ok, i will try this with a 2d collider
god this video is so painful to watch. the way he drags words at the end of the sentence is infuriating
My mouse and all input freezes when running this:
using System.Collections.Generic;
using UnityEngine;
public class CharMovement : MonoBehaviour
{
public float playerSpeed = 50.0f;
public float rotateSpeed = 100.0f;
// Start is called before the first frame update
void Start(){}
void mouselock(){
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Escape)){Cursor.lockState=CursorLockMode.None;}
if(Input.GetKeyDown(KeyCode.Mouse0)){Cursor.lockState=CursorLockMode.Locked;}
while(Cursor.lockState==CursorLockMode.Locked){
float forbac = Input.GetAxis("Vertical") * playerSpeed * Time.deltaTime;
float lefrig = Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime;
float rotation = Input.GetAxis("Mouse X") * rotateSpeed * Time.deltaTime;
transform.Translate(lefrig, 0, forbac);
transform.Rotate(0, rotation, 0);
}
}
}```
you have an obvious infinite loop here
replace while with if
so i can't use while in the update method?
you can use while anywhere you want
you can't use while when the condition will never become false
or you have an infinite loop
such as here
look inside that loop. The entirety of the game engine and all your code will not continue doing anything until your loop finishes executing.
There is nothing inside the loop that can ever change Cursor.lockState. Since it can't change inside the loop - you will be stuck in the loop forver
hence - Unity frozen
Ah
Update runs once per frame. Seems like all you want to do is run that code once per frame while the cursor is locked.
A simple if is sufficient.
So it also won't work if i put this in the while loop because it never updates to check it? if(Input.GetKeyDown(KeyCode.Escape)){Cursor.lockState=CursorLockMode.None;}
yes input only updates once a frame
when you put a while loop in, the loop runs to completion instantly
the game engine is not going to continue in the meantime
it's waiting for your code to finish
before it can move to the next frame
That's the whole point of Update
it runs from top to bottom once every frame
it never even gets a chance to check - because you're stuck in the loop
it's a common misconception that stuff happens "at the same time"
there is one main thread, and we all have to share it
(preemptive multitasking would be when mom says it's your turn on the thread, but that doesn't happen here)
Can I have my turn on it soon?
I made a game using tilemap. When I play the game everything is looking right. When I sent it to my friends to play, they have the right and left side cropped and can't see the walls. Found out it's because they use other resolution than mine (1920x1080). How can I make everything fit in the screen, including the whole tilemap? I know that i can anchor the ui but that doesn't solve the whole tilemap not fitting
is there a more convenient way of making Dictionary appear in inspector than doing an array of [Serializable] structs with 2 fields and then converting to Dictionary in code?
You can get the current resolution by using Screen.width and Screen.height, compare those, and then scale camera's orthographicSize accordingly. Also you would probably want something to fill the gaps between tilemap and the screen edges.
Why does this give an error? I want to reference a static method inside MouseLock class, the object (CodeCube) has the 2 components
MouseLock.cs
using System.Collections.Generic;
using UnityEngine;
static public class MouseLock
{
static public void MouseLockMethod()
{
// if(Input.GetKeyDown(KeyCode.Escape)){Cursor.lockState=CursorLockMode.None;}
if(Input.GetKeyDown(KeyCode.Mouse0)){Cursor.lockState=CursorLockMode.Locked;}
}
}
You can call methods only inside other methods. You've tried to call it inside a class (line 8).
The tilemap is atleast 3 times as big as the camera, so that won't be a problem ( i hope ) Thanks!
using System.Collections.Generic;
using UnityEngine;
public class Main : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
CodeCube.GetComponent<MouseLock>();
}
// Update is called once per frame
void Update()
{
MouseLock.MouseLockMethod();
}
}
``` CodeCube does not exist in current context
It means you haven't declared what is CodeCube. Computer doesn't know what to do with it if it doesn't know what it is.
How can i declare CodeCube? It's an 3d cube object with the 2 C# components
the name of any objects in your scene is irrelevant: that type does not exist
are you trying to find a game object named CodeCube?
Can i reference other C# scripts without it being a component of an object
sure, declare a field of type MouseLock on Main
e.g. public MouseLock mouseLock;
drag the "CodeCube" object into that field
you'll get a reference to its MouseLock component
you can't just type the name of a game object in C# and wind up with the object
I need help. So I have scene changer and it should work but it doesn't. Here is the script :
using UnityEngine;
using UnityEngine.SceneManagement;
using Photon.Pun;
public class SceneSwitcher : MonoBehaviour
{
public string sceneName;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("HandTag"))
{
SceneManager.LoadScene(sceneName);
if (PhotonNetwork.InRoom)
PhotonNetwork.LeaveRoom();
}
}
}
Yes I have added my scene to Build Settings and it is still not working. Can somebody help me?
What is mouselock? the name of the variable on which the MouseLock type is attached?
you declared a MouseLock class
mouseLock is the name of the variable. it can be anything.
in the MouseLock.cs ?
using System.Collections.Generic;
using UnityEngine;
static public class MouseLock
{
static public void MouseLockMethod()
{
// if(Input.GetKeyDown(KeyCode.Escape)){Cursor.lockState=CursorLockMode.None;}
if(Input.GetKeyDown(KeyCode.Mouse0)){Cursor.lockState=CursorLockMode.Locked;}
}
}
did you create a C# script and then edit it afterwards?
So with mouselock i can use the method
this used to be a component
yeah
which is also what this code is trying to do
CodeCube.GetComponent<MouseLock>();
well, MouseLock is now a static class, and doesn't derive from MonoBehaviour
so it is no longer a valid component
if you want MouseLock to be a static class, then this will be fine, I guess. You can write MouseLock.MouseLockMethod() to call the method.
Anyone know a good way to display AudioSource.time as an actual time value?
Building a small audio-player in my game and want to display the actual timestamp values for a songs progress, but running into this issue.
Should display 0:71 as 1:11 instead.
you will have to remove the component from the cube in your scene, because it's no longer a valid component
Shouldn't it be mouselock.MouseLockMethod();?
no, because mouselock is neither the name of a type nor the name of a variable
there is no such thing as mouselock
?
that would be mouseLock. it's also irrelevant now that I see that MouseLock is a static class
you could just look up how to convert seconds into minutes and seconds
i thought it was a component, because you showed a screenshot of it being a component
Yeah i thought it needed to be a component
if it's just going to be a static class, then you don't need to (and can't) put it in a variable
That's why i attached it to the CodeCube
so, just MouseLock.SomeMethod();
that absolutely works ty
And if the MouseLock.cs is in a different directory how do i reference it? how does it know where MouseLock class is?
A few basic ways to get references in Unity.
Directly-
GetComponent 0:38
/GetComponentInChildren
/GetComponentInParent
Public Variable- 3:00
Find- 5:01
Find 5:39 (by name)
FindWithTag 6:14 (by tag)
FindObjectOfType 6:51 (by component)
Interaction- 7:15
OnCollisionEnter
/OnTriggerEnter
you should start with some Unity basics
check out Unity Learn
and #π»βcode-beginner in the future
thanks
yes
Is there a way to change the opacity/alpha of a colour without having to re-reference the original colour? Something like "color.a = x" instead of having to declare "new Color(r, g, b, a)" again
π§βπ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
no
Damn, I was hoping I just missed it all this time, thanks
what? of course you can
you just can't do it if the color was returned from a method or property
since it's a struct, which means it's a value type
so you'd be changing a copy, which would do nothing
it's why you can't do transform.position.y += 1
you can totally just do
Color x = new Color(1, 0, 0, 1);
x.g = 1;
Is there any article / youtube clip which I can watch/read that will help me to structure scripts inside the project better? Any help would be great π»
Try using Assembly Definitions if you aren't already
I'll check It, thanks!
And namespaces! They're nice to separate sections of project
namespacing your project well sounds like a good way to figure out how you'll do assembly definitions down the road
ive got a 2d isometric grid and i want the camera to be able to rotate around the grid to see it at 4 different angles. with an isometric setup is it easier to change the cameras rotation or do you have to rotate the grid and everything on it, havent had much luck figuring out how to rotate the camera around the grid
make an empty object as a child of the grid.
make the camera a child of that empty object
rotate the empty object
cool, that makes sense to me and will attempt that. thanks. i have objects on the grid will those all need to be children of the grid im assuming
yeah, using empties makes things a lot easier
put the empty at the center of the grid and then spin it around the y axis
hey, that just gave me an idea for a strategy game
the camera rotates 90 degrees every turn, and only visible units can act or be targeted
This is always returning with a count of 0 any clues why?
public List<Tile> GetAllTilesInRange(Vector2Int pos, float maxrange, float minrange)
{
return tiles.Values.Where(t => Vector2.Distance(t.Pos, pos) <= maxrange-.5 && Vector2Int.Distance(t.Pos, pos) >= minrange+.5).ToList();
}
that is cool
you have the arguments in the opposite order that I'd expect
are you doing something like GetAllTilesInRange(pos, 3, 5)
i'd expect min, then max
Oh
that would cause you to get no results
Ez fix for future-proofing
if (max < min)
(min, max) = (max, min); // swap!
Ty chem always coming in to help my inability to properly process < > statements
the statements themselves were fine
it was just an unintuitive argument order
you shouldn't need to change the implementation
π
Funily enough the issue was that i set the max and min values wrong on the objects i was getting them from XD
When building my game in dev mode and running it, I'm getting this error seemingly every Update tick
Anyone know what could be going on? It's not appearing in normal unity play mode and seems to be from the Debug Handler itself (so it shouldn't really be a problem but it's still clogging my log files)
report a bug I suppose?
Sure
Does anyone know how to do GUI.RenderTextureWithTexCoords() with the Graphics class like if Graphics.RenderTextureWithTexCoords() existed (which it doesnt). I have a 9slicing function that relies on IMGUI for this, but I want to draw it on a RenderTexture which I don't think IMGUI can do, so I need to figure out how to do this with the Graphics class.
Graphics does have built in 9slicing, but it relies on stretching instead of tiling, so I can't use it.
I am interested in ECS Vs OOP but seems Unity's own ECS might be a bit new & complicated in its desire for speed. Has anyone used other ECS frameworks?
{
HashSet<Cell> area = new();
Debug.Log($"area first: {area.Count}");
foreach (Vector3Int relativeNeighborCubicPosition in HexMath.RelativeNeighborCubicPositions)
{
Vector3Int neighborPosition = centerCoordinate + relativeNeighborCubicPosition * radius;
if (GetCell(neighborPosition, out Cell cell)) area.Add(cell);
for (int r = 1; r < radius; r++)
{
neighborPosition += HexMath.RelativeNeighborCubicPositions[(r+3)%6];
if (GetCell(neighborPosition, out Cell c)) area.Add(c);
}
}
Debug.Log($"area: {area.Count}");
return area;
}```
The first debug is being called but not the second debug. No exceptions are being thrown (just, no area is being returned apparently)
how in the world is that possible
Yep that's not possible. Nothing can exit out of the loop early, except an exception being thrown
not sure if this is the right place, but how do i add this third scene to my hierarchy?
just drag it in from the Project window
that will additively load the scene
i'm fuzzy on how that works after that, though
i really need to learn more about additive scenes
just keeps it loaded until you rightclick > unload
does that mean that it'll always be additively loaded in the scene you added it to?
i've only ever done it by accident lmao
So the code works fine (both debugs call) when all the cells are present (GetCell == true), but if any one of the GetCell returns false, then the second debug never calls
I think they kinda co-exists
but I can keep playing and there ae no exceptions
Which might be because the method is being called as part of an .OnComplete on a Tween
its editor only
I kinda fucked up my entire project 2 days ago when i tried to put every thing on git for safety but ended up deleting my entire project with git reset --hard
scene is added to scene stage/context
it is cool because you can do exactly that on runtime
right
it'd just be nice to not have difference between "i did it in the editor" and "i did it in the player"
create a scene composition, for example dump all your systems in one scene, then load the content scene additively
even better you can avoid doing all the usual singletons/prefabs in work scenes mumbo-jumbo if you hook the editor to first load the scene with your systems then the scene that was just opened
Are you sure you've got errors enabled in the console? Same thing for the Collapse option, which makes similar logs stack with a count on the right of the message.
Try with a try/catch in the OnComplete callback
can you elaborate on that?
not quite following the "hook the editor" part
hmm... still nothing
No, try/catch inside OnComplete( [[ HERE ]] )
Make that a bodied lambda
.OnComplete(() => { try ... catch })
EditorSceneManager.playModeStartScene
EditorApplication.playModeStateChanged
couple key apis
hm, I will have to look into that!
looks scary
i've liked the idea of having a "systems" scene
in
PlayModeStateChange.ExitingEditMode
you override the scenes that will be loaded, you grab which one is opened now, then load your systems, and the one that was opened additively

probably the modular is being weird or something
Ah there we go, so DOTween indeed swallows exceptions, might want to disable its "safe mode" or whatever it's called. If that's even related to exception swallowing
yes there is an option for that i think
Now that I see the exception, looks like it's thrown in GetCell, which shouldn't be throwing when you pass something out of range, it should return false instead
right its "safe mode"
safe mode swallows, without rethrows or skips
also in options set logging to verbose
Like other methods that implement this "TryX" pattern, int.TryParse(string, out int), yours should be called TryGetCell
ah, that would do it
yes, it's this. If there's no such key then it complains
kind of annoying dealing with null cases with structs
Yeah the first line will throw if the key isn't there
You can just do return _bla.TryGetValue(cubicPosition, out cell)
(yes I was lazy typing the dictionary name)
Surely Rider has a bulk-rename feature
Oh, this just works.
how?
it auto assigns cell I guess
But yes, everything works now
TryGetValue internally does, yes. It's populated before TryGetValue returns, so it's valid code
you cant compile if the parameter marked as out is not assigned
TryGetValue sets the out param
GetCell sets the out param
TryGetValue returns
GetCell returns
^ Order of execution
There's actually a ton of return statements I refactor to use that
Hey, guys! I have a problem. I want to make in my game the highscore to be saved on restart game and whenever I click a difficulty button. Is it somehow possible to do that?
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
Debug.Log("The restart button works");
}```
I have the restart game method right here and that's what I do in that.
I have also this method setdifficulty for the player to interact with the game difficulty
```void SetDifficulty()
{
Debug.Log(gameObject.name + " was clicked");
gameManager.StartGame(difficulty);
}```
I am about to work with playerprefs but don't know where to use them
Theres two things that can help here, You can use Dont destroy on load objects often refered to as DDOL, this will make objects persist over multiple scenes. the other option is that you save stats to files and load them from there, this will save data even when you close the game and re-open it again
dont destroy on load: https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
i would start with the dont destroy on load. You can make data game object that isnt destroyed on load, and get ur data from there
What is the other option you ve suggested?
https://docs.unity3d.com/2020.1/Documentation/Manual/JSONSerialization.html
store it to files using json serialization
hey im having problem with my unity project. i wanted to add ads, and somehow f'ed it up completely. tried restarting unity only to get a compilation error and suggesting to start in safe mode. What are the ads folder names? Ill delete them to get a fresh start
wdym folder names? Uninstall the package if you want to delete it
and fix your compile errors if they're in your files.
i did that multiple times but somehow it doesn't fix the errors
did what?
uninstalling the packages
yes
unisntall it and leave it uninstalled
then go through your compile errors one by one.
i'll try that
so right now its trying to resolve the android dependencies. i've had it before but it just gets stuck at 0%
Hello, I could really use some help
Your script should either check if it is null or you should not destroy the object.```
I can see the line where it happens on and I tried to put an if (gameObject != null) block around it, but now the check for gameObject != null is throwing that error
that would imply that the component itself got destroyed
i forget exactly when that triggers an error
show your code
!code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
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.
just to explain what is happening, I have a single common scene and then I am loading and unloading additional scenes additively
with transitions between them
when I go through scenes in order from the beginning when starting the app, everything works perfectly
Well the correct check would be if (this) or if (this != null)
but
more likely you want to fix the underlying problem
explaining which line this happens on (and perhaps providing the stack trace) would be helpfulk
yeah I do want to fix the underlying problem but for now I want to try to make things better
the script you linked seems not to be the problem
it's in some other script which has a reference to an instance of this one
fixing the underlying problem will make things better
adding a null check will just cause unnecessary waste to go unnoticed
and possibly give you very hard to debug behavior issues in your code.
yes I do need to fix the underlying problem
it's just that I wrote this code over a year ago, and I don't remember everything I did
actually maybe I should share the github link
Hey, I installed a custom package some time ago and it worked great, but for some reason I now have compilation errors saying I'm missing a namespace. Any idea why that would happen?
I don't have any errors in the editor tho only in MVS
regenerate project files from unity external tools menu
Perfect thank you π
Thanks very much, this worked
I am going to fix the underlying issue, I know it is with the transition engine
I've created this complicated thing and need to figure out how it works again and it throwing errors is just making things worse by causing other unrelated problems
Is there a in built way I can draw a shape, like the LineRenderer but filled?
Not entirely clear what you mean by that - maybe you want the SpriteShape package?
https://docs.unity3d.com/Packages/com.unity.2d.spriteshape@10.0/manual/index.html
I've drawn a shape with a line renderer, but I can't fill it.
FIll it?
what kind of end result are you looking for here? A mesh? An image / sprite?
LineRenderer renders lines, that's all it does
A sprite I guess, I was wondering if I could draw vectorial icons or something
Like I would in Illustrator
WHy not do it in Illustrator?
What you're talking about is possible in various ways - but LineRenderer isn't one of them
So what are the possibilities?
Shaders is one I guess
I'm quite illiterate in shaders tho
well it's kind of unclear to me still what you mean by "fill"- but yes:
- a mesh with vertex shaders
- a mesh actually being modified at runtime
- a SpriteRenderer rendering a texture that you modify
LineRenderer can of course also be animated but it cannot be "filled"
it can only draw lines
Makes sense
There's of course assets like this too:
https://assetstore.unity.com/packages/tools/particles-effects/shapes-173167
ok so now that I have that check in there for null I think I can tell what the problem is
I don't know yet why it is happening but I know what the problem is
I think I'm going to leave that in there but I'm going to keep my log warning for if it is null what to do
so that way I can tell if this happens
The idea was to do a Yin-yang, and draw another in each tiny circle, zoom infinitely, and there wouldn't be default cos the symbol is always the same "definition"
before it was throwing so many errors it was very hard to tell what was happening
now with this check all of the errors are gone, and it behaves better but still not perfect, but I can see my log warning from where it goes wrong
I heard about this, sounds pretty cool
Thanks for the info I'll look into it
this might be silly but this error is so confusing to me
public Volume postProcessVolume;
private ChromaticAberration chromaticAberration;
private Vignette vignette;
private Grain grain;
private LensDistortion lensDistortion;```
The type or namespace name 'Volume' could not be found (are you missing a using directive or an assembly reference?)
i am using URP
You're missing a using directive or an assembly reference
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Rendering.PostProcessing;```
nevermind
i needed this
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
alright
i've recently switched over to urp so this is all new to me
although another error when i press play
{
transform.position = respawnPoint.position;
PlayerHealth = startingHealth;
respawnPoint = transform;
deathText.enabled = false;
deathText2.enabled = false;
// Get post-processing effects from the volume
postProcessVolume.profile.TryGet(out chromaticAberration);
postProcessVolume.profile.TryGet(out vignette);
postProcessVolume.profile.TryGet(out grain);
postProcessVolume.profile.TryGet(out lensDistortion);
}```
postProcessVolume.profile.TryGet(out chromaticAberration); is apparently Object reference not set to an instance of an object
that entire thing doesn't seem to work
well, then profile is null
Hey, I have an issue with my script. It looks like my scripts for generating a mesh along a curve get wrong points (despite them being assigned correctly). It gets fixed when I select either the gameobject with the point or gameobject with the scripts.
This is what I get after I generate the entire mesh.
And this is what I get after I just select the mentioned gameobjects, and regenerate the mesh along that curve (this is correct)
why does this happen?
Here are the scripts that are used for this https://gdl.space/ecoxawusat.cs
The way it works, is Intersection.GenerateIntersection() -> LinePlacement.GenerateAlongPath() -> VerticesCollider.GenerateMesh()
(the last function call is not there, but i've added it after realizing it's gone, so it works, but the issue above remains)
Apparently it happens in any case, where the PathPoint needs to be inverted (that is, swapped tangent ends). And it looks like just selecting the gameobject with the Path script, or specific points, then regenerating, fixes it
@leaden ice FYI, I solved the underlying problem
the problem was actually in the code that I pasted
I wasn't unregistering the event manager on destroy
so upon reloading a scene that was previously loaded, two copies of the script were being triggered, the one for the open copy and the one for the previously opened copy
I added an ondestroy function to remove it from the event manager when it was destroyed
Hello! I have a class that loads and transitions scenes and fire events like such:
public class SceneLoader {
private static event UnityAction SceneLoadedEvent;
private static void OnSceneLoadedEvent() => SceneLoadedEvent?.Invoke();
}
I would like to subscribe to the SceneLoadedEvent from other classes without giving public access.
My understanding of C# events is weak, no matter how much documentation I read on it.
Ideally I could subscribe from another class like:
public class UI_LevelLoad {
private void OnEnable()
{
SceneLoader.SceneLoadedEvent_Subscribe(ShowUI, true);
}
private void OnDisable(){
SceneLoader.SceneLoadedEvent_Subscribe(ShowUI, false);
}
private void ShowUI(){
}
}
Just fyi, other classes canβt invoke the event, even if its public, they can only subscribe.
OHH???
Jeez
I was totally overthinking this
Thanks!
im fighting with my unity app and almost throwing my pc out. its not letting me patch and run to my phone like it did before. the error log tells me the "APK is out of sync". Can't find anything about it online.
a bit further down the error it says "this feature requires ASM7"
nvm i changed the target api and it works again
Does anyone at least know more or less how the CharacterController.Move function works?
I don't want to use the built-in CharacterController component, instead opting for my own custom character controller.
my understanding is that it uses https://docs.unity3d.com/ScriptReference/Physics.ComputePenetration.html
although, actually, that doesn't work for non-convex mesh colliders
and the docs mention that
One particular example is an implementation of a character controller where a specific reaction to collision with the surrounding physics objects is required
whilst character controllers don't really have a ... specific reaction
feels more like a capsule cast
Thanks for responding.
I'm more curious about the movement scheme, not the collision. π€
the movement itself should be pretty trivial
if you don't hit anything, you just...move by the amount specified
the interesting part of a character controller is how it deals with collisions
it must be more than just a capsule cast, given how character controllers can climb up slopes and over ledges
Right, but it doesn't seem to use anything like AddForce.
π€
Maybe it's detecting collision and then performing a direct transform.position manipulation?
it merely respects collisions
It's moving like a normal translation update, and then performing collision resolution based on nearby colliders
If it moves into something, all it's going to do is move out of it
If you actually want to understand the underlying collision detection & resolution, then this is probably a good place to start
In geometry, the hyperplane separation theorem is a theorem about disjoint convex sets in n-dimensional Euclidean space. There are several rather similar versions. In one version of the theorem, if both these sets are closed and at least one of them is compact, then there is a hyperplane in between them and even two parallel hyperplanes in betwe...
Again, I'm not as interested in the collision... yet.
I was looking more for how it actually moves the player. If it happens to be a direct transform.position change, then I'll likely need to look into the collision schema again.
I don't have access to unity's source code, but if I had to speculate, it probably isn't performing a real transform update twice
it's just logically updating the collider data and then performing the resolution against that using something like the first link I sent
after the resolution is done, is probably when the actual gameobjects get updated
HST is pretty straightforward. It's just projecting the bounding box onto the normal axes of both potentially colliding objects
if there's a gap of any size between them, they aren't colliding.
but obviously you won't be writing your own HST. Physics.ComputePenetration is more than enough.
CharacterController is actually a PhysX class and the open source code is out there. It's likely more or less just doing a capsule cast and moving as far as the hit distance on the cast allows (or as far as you asked if it hit nothing)
would anyone have some advice for how to resolve overlapping shadows like this?
i was thinking about just doing it through a shader on the sprite material but wasn't sure
unsure what'd be most performant given the high number of trees/etc.
im using navmesh to move agent objects, but they jitter sometimes. it seems to only happen when i instantiate a new agent object and that object's destiantion is set to the same destination as another agent object. How do i stop the jittering?
i guess they're jittering becuase they never reach the destination
Ah, so I'd have to look through a PhysX library then?
do I have to worry about injection when using unity's input field?
If you're executing the string as code somewhere sure
E.g. plugging it into a SQL query
https://gdl.space/okurofeqej.cs
could anyone maybe look through this code and spot anything im doing the wrong way? it all works but i wrote without any help or anything i tried to explain my logic through comments so i didnt get side tracked
i had to rewrite the refresh hotbar a few times thats why its heavily commented
No. Considering it would be pointless to write your own collision solver when unity it quite literally exposing their own.
The point is I want to see how they do it so that I can see how (or how not) to do it for my own controller. See if there's anything for which I'm failing to account.
Or failing to substitute properly.
Unity only provides an extern reference to the move function, meaning it's a function handled externally.
This does not make any sense
I assume this is the PhysX library they use.
I've already explained to you how controllers work internally
nvidia isn't going to do some 180 backwards shit
This jargon is currently meaningless to me. I'm looking for code, not concepts. I want to see the code behind it so I can see it in practice.
In geometry, the hyperplane separation theorem is a theorem about disjoint convex sets in n-dimensional Euclidean space. There are several rather similar versions. In one version of the theorem, if both these sets are closed and at least one of them is compact, then there is a hyperplane in between them and even two parallel hyperplanes in betwe...
here you go
I can't see it in-game currently because the collider generated by the CharacterController is causing all sorts of issues.
Yes, you posted that already.
I was going to look into that next.
So like
why dont you just write your own controller
using unity's method I showed you earlier
@swift falconLooks like I was half-wrong. Looks like Nvidia does sweeptests and depenetration
I might... after I understand how the movement code I acquired is actually supposed to work.
Remember, I have code I'm borrowing.
Oh I don't mind that. π
I don't understand what borrowing code means
Someone else wrote the code.
It's code that faithfully recreates "CPMA-style" movement in Unity.
The only thing is that it takes all of that movement calculation and puts it into a single Vector3, which is then passed to the CharacterController.Move function, in that code.
My own controller uses a Rigidbody component and calls AddForce to propel the player.
You should absolutely not be using rigidbodies and character controllers on the same object.
So currently the movement is not working as it should.
Right, so I'm not.
But now the numbers are all off.
is CPMA doom?
Because if I'm jumping and moving, I'm gonna be accruing plenty of speed.
Actually no, it's Quake 3 Arena.
Yeah, none of this warrants looking at the backend code
you can do everything you've explained above with a character controller. There's nothing stopping you
Not with Unity's, I'd have to make my own somehow.
but why????
The collider it generates interferes with plenty of things.
Especially the projectiles fired from my weapons.
so then place individual collider triggers on each of its limbs lmfao
you're trying to make this too complicated
tell me what else it interferes with
I don't seem to be able to jump.
However I'm not sure if that's due to improperly implemented code or the collider.
I can assure you the character controller jumps fine
if the correct logic is written on top of it
me and millions of other people have done it
for the character hitbox, just put trigger colliders parented to each of the limbs
it's that easy
you can put your character controller on a separate layer and have your bullets ignore it
I'm making a unity 2D game with ragdoll physics. The game revolves around a stickman which is able to aim weapons, where the weapons rotate towards the mouse position. An example issue I'm facing when aiming a weapon is that if the mouse is quickly moved from the right, then over the player ending in the left side of the screen, the player's rotation will be calculated wrong, resulting in the players arms being bent, no longer following the mouse correctly. How can this issue be resolved?
Attached is a video demonstrating the issue, as my articulate skills are not the best
For more information feel free to ask
Please @rose token
Don't cross post #πβcode-of-conduct #π»βcode-beginner message
whoops, sorry
Guys, when I try to set position of the player when I have CharacterController I don't get any changes to the my position.
What's the problem?
CC disables the changes made to Transform.
Please no reaction gifs.
Call https://docs.unity3d.com/ScriptReference/Physics.SyncTransforms.html to sync the transform or https://docs.unity3d.com/ScriptReference/Physics-autoSyncTransforms.html to have it auto sync.
;*(
i have 2 items of the same class that hold the variable int amount
how would i calculate the combine amount? say for instance i have 2 items in my inventory the items have a max stack of 5
1 item has the amount of 3 and the other item has the amount of 3 how would i add 3 + 3 and get the remainder?
Assuming you have the current held items in a class-scoped list called items:
var totalAmount = this.items.Sum(x => x.amount);
Note that this is a Linq function, and required the import of System.Linq namespace.
the 2 Slots are seperate and not in a list
How does your inventory keep track of the items, then?
its hard to explain but what im setting is 2 differnt values of the same list
they are cached as SlotClass
You should share your code
Not much I can do to answer when your setup is different to what I would expect
So they're all a SlotClass?
What is in that?
just data thats stored and methods for that specific slot class e.g item, amount and Constructors
ill share the code
So if amount is in there, how is my code not a solution?
You just need to allow amount to be accessed outside the class using a property, or by making it public
You actually already have that, with GetAmount
var totalAmount = this.items.Sum(x => x.GetAmount());
ngl i cant see how it would compare the 2 values
You mean there is more to collect?
As in, there are more amounts that should add to the sum?
moving_slot is cached when clicked on and nearest slot is cached inside the function when a player clicks on an empty slot
or on a slot thats stackable
Well you could add those to the function if you need them
var totalAmount = this.items
.Concat(new[] { this.moving_slot, this.nearest_slot })
.Sum(x => x.GetAmount());
Unless I'm not understanding correctly
i need to find the difference after the value has been added when it reaches a stack of 5 but theres 6 items i need to be able to set the moving slot to 1 as thats the amount thats left
I'm not sure what you mean
right so if i pickup an item in a slot that has a stack size of 3
i go to place that item in another slot that has 3 but the max stack size for that item is 5 ill have 1 item left over
thats what im trying to calculate
Hi, Instead of using singleton, I'm trying to create a subclass of my GameManager using Inheritance. E.g. ConnectionManager : GameManager The only issue i'm having is that now the ConnectionManager serializes all components from the gamemanager in the inspector. I just want it to serialize its own class. How can i go about doing that? or is my architecture that is flawed from the start?
you want to serialize GameManager?
Yes GameManager has properties i want to serialize but i dont want them shown in connection manager since it should use the same properties
I'm starting to think the architecture is flawed and im using inheritence wrong.
well If connection manager inherits from GameManager all the serialized variables inside GameManager will show on the inspector anyways on what ever ConnectionManager sits on
yea the connection manager sits on the gamemanager...i just wanted to split up the code into different classes
I also didnt want to make the variables public...so i was using protected.
yea
what do you want to show in the inspector and what do you not want to show in the inspector?
if your wanting to use varibles and methods from GameManager but dont want them to be shown in the inspector id just recommend making gamemanager a singleton rather than inherriting from it
I want the Variables shown in the GameManager class to show in the inspector for the GameManager class only. Then the ConnectionManager can use the GameManager Variables and change them but will only show Its variables in the inspector
I guess i should probably use singleton yea...but then it makes the GM public and i didn't really want that.
whats wrong with it being public?
idk potential security risks?
are you just reading variables from connection manager?
its for a multiplayer game and i kinda wanted a lockdown
no i think its reading and changing
i was going to say use protected readonly field
Also since I'm using the variables so often its going to be annyoing to put GameManager.Instance.##Variable## every time i use it no?
will look very messy
still then need to put gm.#Variable## each time aswell
i have like over 100 use cases just in this class...probably alot more in others
you can use the [HideInInspector] attribute no?
but i still want it searilized for GM class
anything you dont want showing up inside the inspector you can use https://docs.unity3d.com/ScriptReference/HideInInspector.html
One sec. If im doing ConnectionManager : GameManager when i change values in Connection Manager...will it change the values in the gamemanager?
it will show the base serialized data from GameManager if there is any
right...yea im doing this wrong
for instance i have a scriptable object called item
and another that has inheritted from item
it will show the base serialized data from item and the data ive also serialized in the other class
All i want to do really is break down the GameManager class into submanager classes that can use and alter the base variables in gamemanager.
was thinking that
might be your best option tbf
namespace + singleton you mean?
singletons are only accessible when the script has been instantiated
What methods are called when I select a game object, and how can I call them myself?
select how?
Like, click on the game object in the hierarchy, or just in the scene view. Anything, so it's selected
Hm, doesn't seem like this is what I need, I guess I have to dig deeper. But thanks nevertheless!
nws π
Generally I'm trying to find some way around this issue, and I thought that if selecting an object fixes it, then that might be some idea for where to start
ur issue is that the mesh is incorrectly generating or z fighting?
Incorrectly generating. Although the points given to the script generating it are correct
As you can see, it does well for every other part of the road, but not this one.
its most likely a code issue then tbf
infact
if ur editor fixes it when its been selected it cant be
Ye, that's what I thought
hows it look in the game view?
It seems like, when I select the game object with that script, it does kinda refresh it or something. Or maybe there's some stuff in the OnSceneGUI or OnInspectorGUI (editor for Path script) that I didn't notice.
I actually didn't think of checking this. I'll get onto my PC when I can and send you a screenshot
are you able to replicate this issue on a different version of the unity editor?
alrighty π
Again, I'd have to check. I am using beta rn, not LTS, so there might be something to it. But then I cannot really go back to LTS because [long list of reasons]
yeah there could be a bug in the that versions render pipeline
i wish my school did game dev :/
I wish the same, but then I realize how bad are schools in my country at teaching stuff, so it's probably for the better that we don't learn that
ah i see, here in the uk well i cant really say anything im 17 and i havent been to school in like 4 years
Luckily I'm studying at the university already, and here it's better. And we can pick gamedev as specialization later on (probably).
ah i see π
Btw, as for zfighting, any idea on how to easily fix it? What I'm doing now, is just raise every next part by 0.0001f on Y axis, and it works. But still there are 3+ overlapping meshes
hmm im not really too sure im not really good with this type of stuff my self
there are some ways to fix tho
Hm... Those are quite basic. I think probably the most optimal way would be to change how mesh is being rendered, but then that is complicated
And since there are other games that do it similarly to how I do it, there's nothing to worry about I think
Yeah haha, i dont know much about these kinda things as im just learning myself π
Understandable, I'm learning that stuff too. But all I can say as of now is that procedural mesh generation is a great thing
Mind if I DM you later with that? It might take quite a while until I can access my PC, and I don't want to reply to some old message when new people with new problems come
Yeah sure π
Hi, I'm making a 1v1 football game and when I move the two characters/objects, they move at the same time. I need someone to help me make a code to control a character with wasd and another with the little arrows.
post code in #π»βcode-beginner
hey im trying to integrate ads in my mobile game. I'm using admob from google. I added my phone as a test device and a banner on the home screen as test. on my pc when i run it i see the banner, but i dont see it on my phone. Anyone an idea?
Check the logs in logcat or something. See if there are any errors or other info related to the ads.
Im checking right now but it's not giving me any errors. what should i look for in the logs?
Depending on the verbosity level of the ads library, it should output info like, "requesting ad", "displaying ad" and such.
If it doesn't, see if you can elevate the verbosity level and rebuild your app.
i have it on the highest right now, but cannot see anything about ads
what i do see tho thta it's trying to resize something when i press the ad button
(it should display a banner when i press the ad button)
Are there any github engineers able to help me with my github setup? I'm using git lfs, and for some reason I keep getting files which appear seemingly randomly, then refuse to get discarded. The only way to get rid of these files is to run a series of git commands, only for them to later reappear. thanks in advance
It should at least have some logs on the ads initialization. If it doesn't, then you don't have the required components in the scene.
Or you're filtering out the relevant logs
i dont think i have any filters on, haven't added them
And when i search for "ads" nothing shows up
It might not use that word exactly. You should be able to see some logs in the editor and look for similar logs in the logcat.
Also, you said the verbosity is set to high, but what other options are there?
there is
verbose(show all)
Debug
info(default)
warning
error
fatal(highest priority)
And what is it set to?
verbose (Show all)
Okay. Then you should be able to see at least some logs, if your setup is correct.
well the weird thing is, no i don't see anything that has to do with ads
Are there any logs when you play in the editor?
Do the "Initialization complete" logs appear in the logcat?
nope
Maybe look into the ads manager script and add some logs of your own to see what's going on. Or even connect a debugger and step through the code.
i'll add some logs in the start function, and in the function of the banner. I'll see whay i can ind
I don't understand how you can throw NullReferenceException and point to the line where I check if thing is null
if (myClassInstance != null)
how in the world this line can throw an exceptionπ€·ββοΈ
for some reason the debugs are not showing up either...
tried in multiple scripts but none are showing
Are you sure the correct scene is included in the build?
I added a debug on the scene change, and even that did not show
It shouldn't. That's probably not the correct line. Or you're omitting something important in your quote.
I triple checked, it points to line 22, and this is the line 22
I don't get how an if null check can throw NRE
Welp, either, none of the changes are included in the build, or there's something with the logcat or how you use it.
Is that how the line actually looks in your code?
i'll download a new one, see if that might help
It wouldn't.
I don't think the version is the problem. More likely the way you use it.
no. it's
if (piecesManager.draggedPiece != null)
draggedPiece is a MonoBehaviour
Now that's better. That CAN throw an NRE
please don't simplify your code when asking a question
Here, piecesManager is probably null
no
yes
Errors says otherwise
Otherwise there wouldn't be an error
It was null at the time this line ran
I'm not simplifying, I'm generalizing. many times code doesn't make sense to anybody other than me
That's not a generalization. Accessing another class instance field vs accessing a field on this is an important difference.
who said that myClassInstance is on this?
wat
Because that's how it would be if it was an actual code..?

Ah, yeah this is never null, hence the difference
That question doesn't really make sense. It's like arguing that 2+2 is not 4...
no, it's like assuming 2+2 is 4 without knowing underlying math
There's no underlying math here.
Anyways, if you don't need any more help, there's no point in dragging this on.
My head hurts.
Anyway, check for git conflicts if you are using it, had a guy yesterday with an error that made no sense. Was a conflict with git.
I can't really think of what would cause that normally.
Or perhaps the thing you are pulling .draggedPiece from is null. That is, piecesManager.
Nothing, it's just that they generalised and got rid of what could throw such exception when posting here
Yeah, the manager was null here
a != null can't throw, a.b != null can (assuming a is a field)
ok apparently it was an issue with static fields because of disabled domain reload
Which was making it null.
i can assure you that removing context will not help me understand your code
Looks like this isn't a UnityEvent, but a regular C# event. There's no AddListener on that, you need to subscribe the C# way:
diff.onClick += () => { /* ... */ }
(note that using a lambda, you will not be able to unsubscribe from it)
Read the error and apply the solution in it.
thanks, no errors, I guess it should work now
so I cam to the conclusion that i dont even need a while loop because what Im trying to do does not correspond to any loop. so would this script work: https://hatebin.com/hmpqqlhcqb
It would definitely compile, but it probably wouldn't work the way you intend it to(depending on what you intend though).
its a teleporter
never mind, now it throws:
InvalidCastException: Specified cast is not valid.
SpawnManager.Start () (at Assets/#Scripts/SpawnManager.cs:37)
private void Start()
{
scoreManager = GetComponent<ScoreManager>();
foreach (Button diff in difficultiesGm.transform)
{
diff.clicked += () =>
{
Debug.Log("nice");
};
}
}
so it teleports the player to the targetTeleporter
That much I figured
and after you teleport, the teleporter goes on a cooldown on both ends
Well, the cooldown part is probably not gonna work
oh i know that
i need to do that
I need it so if the just teleported is true, it will ignore all collisions
It's your foreach loop. Iterating over transform doesn't output Button, it outputs Transform values. You need to do foreach (Transform t in difficultiesGm.transform) and then call t.GetComponent<Button>() on it to get the button
And why did you move to this channel. Please don't crosspost. #π»βcode-beginner is the right place.
yes, have done it already, throws two more errors
NullReferenceException?
what a pity, no
oh, do not mention Destroy error
private void Start()
{
scoreManager = GetComponent<ScoreManager>();
foreach (Transform diff in difficultiesGm.transform)
{
diff.GetComponent<Button>().clicked += () =>
{
Debug.Log("nice");
};
}
}
Oh, so that Button you pass in there isn't what you think it is. Do you have your own class named that?
no, I don't
Hover over it in your code editor, what appears in the tooltip? It should mention the full namespace of that Button type
thank you, it works now
private void Start()
{
foreach (Transform diff in difficultiesGm.transform)
{
diff.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() =>
{
Debug.Log("nice");
});
}
}
Yeah it was picking up another Button class, if this works
you might have a class called Button
yeah, it was picking UnityEngine.UIElements.Button
nop
Ah that'll do it
Also consider using Text Mesh Pro, the UnityEngine.UI stuff is old now
diff.GetComponent<UnityEngine.UIElements.Button>().clicked += () =>
{
Debug.Log("nice");
};
Button still comes from UnityEngine.UI
there is no special text mesh pro button component
Ah, uhh so it's Dropdown that has its own TMP right?
the "text mesh pro" version in the GameObject menu just uses a TMP text component instead of the legacy one
I have used Button - TextMeshPro π
yeah, there's a special TMP_Dropdown
Yeah that'll work, as TMP buttons are just normal buttons but with a TMP Text to render the text you need to show
yes, they are
and TMP is better, so Buttons that use TMP are also better
TMP > all
that's not question, but may I ask you how have you done time zone in you bio?
Oh it uses discord's markdown to render a timestamp hang on
12:00 PM for me is <t:1641034800:t> for you
thank you
oh right, you can just use that directly
Basically, first <t: is for MD to recognize it. Then the number is the Unix timestamp of some date, any date as long as it's on 12pm, then the second t is the format specifier for "short time"
What can make a component's OnEnable() trigger before another component on the same object Awake(), I thought it should be all Awakes in scene, then OnEnable() if component is enabled