#💻┃code-beginner
1 messages · Page 163 of 1
yeah cause i removed it
or that is is reseted to 50 before each frame
It's not a property which was misunderstood #💻┃code-beginner message
what currently exists is fine, though
It's actually kind of ideal, since it'll completely ignore anything that happens to the lens settings whilst the coroutine is running
which rules some stuff out
oh wait no i was debugging m_Lens.orthographic size and not lensSettings.orthographic size
lol
lensSettings.orthographicSize goes down to 5
Maybe show the code now
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class SpawnCutsceneScriptCompanion : MonoBehaviour
{
public CinemachineVirtualCamera VC;
public GameObject player;
// Start is called before the first frame update
void Start()
{
StartCoroutine(Delay());
}
// Update is called once per frame
void Update()
{
}
private IEnumerator Delay()
{
yield return new WaitForSeconds(4f);
Vector3 deltaPos = player.transform.position - VC.transform.position;
float timePassed = 0;
var lensSettings = VC.m_Lens;
while (timePassed < 1f)
{
timePassed += Time.deltaTime;
VC.transform.position += deltaPos * Time.deltaTime;
VC.transform.position = new Vector3(VC.transform.position.x, VC.transform.position.y, -35);
lensSettings.OrthographicSize -= 45 * Time.deltaTime;
VC.m_Lens = lensSettings;
Debug.Log(lensSettings.OrthographicSize);
yield return null;
}
VC.transform.position = player.transform.position;
VC.Follow = player.transform;
}
}```
How many console messages are you getting? Screenshot your console after the coroutine ends.
I suspect you're creating many copies of SpawnCutsceneScriptCompanion, which is starting many copies of the coroutine. You could check that by logging when Start() runs.
okay, just 129 messages, which is consistent with only one copy of the coroutine running
so the variable is changing but the actual value of the camera isnt changing
click on m_Lens and hit Shift-F12
we are going to search for every place you use that field
when you log VC.m_Lens.OrthographicSize it isn't changing ?
given everything we've seen, I think something else is also writing to m_Lens
For example
You might have code that's trying to set it to 50 every frame
only by like 0.46
Hey, so I have an array of 3 objects and from either the first or second object in the array I switch to the 3rd object as the current index. I want a way to somehow keep track wether I switched from the first or the second object and be able to reference it/ know its index. Please help
although that doesn't square up with the slight decrease you're seeing
help i renamed a scene before i saved, is there a way to get back what i changed?
"before i saved"?
i don't understand the problem. your scene has a new name now
renaming the currently-open scene should be fine
ye but i added a bucnh fo UI elements that now are gone
You'd keep track where you'd switch
it reloaded the scene
just remember the old index, I presume
the only other script in this scene is the player movement and procedural dungeon script both scripts dont refrence any sort of cameras
okay, cool, but do this anyway #💻┃code-beginner message
I get that but as a beginner I dont know how to do that. sorry
can someone tell me why visual studio dont auto complement the code please?
and after the end of the corouting it is still at like 49. something ?
and yes i have this
no it says 50 in editor but 49. something in console
previous = current
current = next```it would be dependent on your switching number feature
what says 49.6 in the console?
can you try changing the execution order of your script to make it execute last on each frame ?
Debug.Log(lensSettings.OrthographicSize); ?
you showed us that the console logs values ranging from 50 to 5
does unity c# script run in order that the lines are written?
did you add a line that lots VC.m_Lens.OrthographicSize ?
of course.
how do you know what the "current" thing is?
do you store an integer that you used to index the array, like this?
private int current;
void Update() {
Debug.Log("The current thing is : " + items[current]);
}
no i was talking about when i was logging that before
I really can't follow you. You need to be way more explicit about what you're doing.
there are several kinds of numbers here and it's extremely confusing when you just talk about them without context
also, please: #💻┃code-beginner message
you can do something like this ```
var myArr = object[3];
int index = Random.Range(0, 2); // gets either 0 or 1
myArr[2] = myArr[index];
// you can still use index or myArr[index]
We'd need more context. As is, I'm assuming this bit of code isn't inside the body of a class
they're trying to declare a method
i don't know if you actually get autocompletion for Unity message names
Yeah, it'd really depend on how they're switching numbers in the first place
(it certainly doesn't happen in VSCode for me)
I haven't used VSC for quite some time but when I did, an extension inserted them for me (before the new configuration)
well you definitely won't get autocompletion for unity message names inside of another method
those names are only meaningful when declaring methods in a class
Maybe your ide isn't configured
you should see if you're getting completions for, say, transform inside the Update method
Can you post the entire !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.
Your IDE is not configured properly.
oncoll can not be a valid method return type, how should it auto complete?
- Run the visual studio installer
- Click modify
- on the right at
game development with unity, is intellicode ticked ?
Follow all of the steps in the !ide instructions
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
you need this installed, but there are more steps.
what are those steps?
ah this
Yeah, it's not configured properly. Do the steps and see if it works. If you get stuck in any step, feel free to ask the channel for help
the instructions are available in spanish if that works better for you
i noticed you sent a screenshot with Spanish text
why cant i find the method?
@cobalt sentinel have you looked at this
i have it
here
you've dragged a script asset into the field
Did you reference an instance with the component script in the scene or the prefab script?
you're trying to do stuff to the script asset (the thing unity creates from your .cs file)
The method isn't static so it'll only be available for instances
oh i see
you probably meant to drag an actual instance of the ButtonManager class into the field.
i.e. a component you've attached to a game object
even if it was static, MonoScript is editor-only
this is targeting the literal script asset
Hey, when i start a new project, i have this error, can maybe someone help me ?
hey, first of all: i hope this is the right place to ask. I am fairly new to unity and want to seek some advice.
I want to have a dynamic ecg in my game and was wondering what the best approach would be.
My ideas:
- Make the ecg a moving png (Pro: low programing needed (probalby), special waveforms easy to show ; Con: every wave-form must be handmade beforehand, max frequenzy is limited because qrs-complex cant overlap)
- Use a dynamic chart taking its data from a list updating at 50hz (Pro: very customizable, small differences can be made (same diagnosis does not look exactly the same ; Con: more programing, high resource needed?? (i dont know about this))
- Way i dont know yet (Probably because i have little to no idea how to do this)
Would be very happy if someone could tell me if 1/2 are actually doable and what might be the best option.
not a code problem. ask about this in #💻┃unity-talk
PS: Sorry for my english-skills... i am not a native
thank you i will
I was talking to Mathis.
Is this going to be a core part of your game?
like, you're being asked to interpret EKG charts?
Well, probably also relative to #💻┃unity-talk
correct yes
It's closer to a code problem at least :p
Looks like a design problem
I think this is a good application for AnimationCurves.
Each part of an EKG waveform can be modeled as a separate animation curve. You can then sum up several curves to produce the final waveform
i think you can do this pretty easily with a LineRenderer
thanks a lot everyone, it worked
You would then use a LineRenderer to actually draw the line, yes
you need to compute a sum of waveforms ?
For example, you'd store the Q wave like this.
then, if you want to display a chart with a missing Q wave, or a badly-timed Q wave, you'd just mess with how you sample the animation curve
can i dynamicly change the waveforms in a LineRenderer? like slowly rising t-waves indicating beginning infarction?
[SerializeField] AnimationCurve qWave;
public float GetWave(float t) {
float result = 0;
result += qWave(t);
}
you can do whatever you want in the LineRenderer
you just need to figure out how to compute the values to display with the LineRenderer
the button has now the script as a component, u meant this ye?
a line renderer is just a set of points that are drawn together with lines
this could be easily extended
[SerializeField] float qWaveOffset;
[SerializeField] AnimationCurve qWave;
public float GetWave(float t) {
float result = 0;
result += qWave(t + qWaveOffset);
}
now you can push the Q wave around
That's what first comes to mind. Make a bunch of AnimationCurves, one for each major feature of the EKG
to which you can add some configurations such as differents widths in various places of the shape
You could even make a ScriptableObject that holds the animation curve, so that you can make an asset for each wave type. Then you could make a list of those assets.
thank you very much! i will look into the linerenderer
yes, now you need to click No Function > ButtonsManager > Restart
one annoying thing with the line renderer is that you'll need to move all of the points down the list every step
point 0 has to become point 1, point 1 becomes point 2, etc.
yeah i already thought so. atlest thats how i imagined the chart tool i was going to use initialy
ye but uhh..
will my game suffer fps if i use a highly detailed line? like lets say 10hz or something?
also can the linerenderer do sharp edges?
Add in an object with the script on it not the script file
you attached scripts to game objects as components to use them
then this OnClick you drag the game object with the script on it in
ok ty solved
think of a class in a script as a template as just instructions to make something
when you put it on a gameobject is when it becomes what we call a instance which is a real object you can reference
Hello, I looked on the web but could not find a fix from the other things people suggested to try.
My issue is Camera.main.ScreenToWorldPoint(Input.mousePosition) outputs correct position but is offset from the mouse at all time. The axes are fine, so when I move mouse up it moves up or down etc, but it is always bit left and higher than mouse.
Maybe show some code, the hierarchy and the inspector for game object in question?
You'd need to provide more context.
Well I have a generated mesh
I generate the points on Camera.main.ScreenToWorldPoint(Input.mousePosition) since I am not using PointerEventData for one reason
and well, the output of the ScreenToWorld is offset from mouse
The code will be useful to see
sure
trianglesList = new List<int>();
verticesList.Add(transform.position + (stemWidth * Vector3.down));
verticesList.Add(transform.position + (stemWidth * Vector3.up));
verticesList.Add(verticesList[0] + Camera.main.ScreenToWorldPoint(Input.mousePosition));
trianglesList.Add(0);
trianglesList.Add(1);
trianglesList.Add(2);
mesh.vertices = verticesList.ToArray();
mesh.triangles = trianglesList.ToArray();```
note that Camera.main.ScreenToWorldPoint(Input.mousePosition) is going to give you a point on the camera's near clipping plane
then you should absolutely be more careful about the z position you want
because this is going to be way offset on the z axis most likely from your other vertices
I assumed I can ignore the Z when there is kinda only importance in XY?
also note that vertex positions for a mesh are in local space of the object. ScreenToWorld produces a world space position
you can never ignore z
well not in distance and other methods
but in here I thought i can
anyway, offtopic
mhm
I suspect this is likely your main issue though
How do I change it from local to global then
I know how to change GameObject transform ones
Vector3 localPos = transform.InverseTransformPoint(worldPos);
you'll want to use the Transform of the GO that the MeshRenderer is attached to
yup
its all on one object fortunately
its kinda placeholder showing the final object size
Thanks for help
trying now
no, still offset 😐
I ll make a video maybe
And also reset Z to 0, just in case
Ah wait you're also doing verticesList.Add(transform.position + (stemWidth * Vector3.down)); inside here?
That's sketchy
now you're incorporating world space positions into these local space positions
yup
but those works
since I create the object on the correct world coords
verticesList.Add(verticesList[0] + transform.InverseTransformPoint(Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0))));
trying this now
0 is incorrect
you would want the distance of the camera to the object
ah yeah, I am slightly recalling it was something like that
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
worldPoint.z = transform.position.z;
verticesList.Add(transform.InverseTransformPoint(worldPoint));``` no?
why verticesList[0] + ?
might be redundant
yeah it is
yay it works
well not exactly fully but at least the vertex at mouse does 😄
for some reason now the other two points pop up elsewhere than where I Instantiate the object
but I dont want to bother you unless?
I suspect because you're adding world space positions into it
Which doesn't make sense
technically if it were up to me I d love to work in world space all the time 😄
I think you need to remove transform.position + from those other points
well you're stuck with local space since that's how mesh coordinates work
I have all main objects at 0 0 0 so technically I rarely used local positions
is there a disadvantage to using Awake compared to Start?
They run at different times
If you need to to happen on Awake, put it in Awake. If you need it to happen on Start, put it in Start
cuz imma use Awake to rerun the code whenevr the script is initialized
cuz when i restart the scene
the values i set in start dont get reset to what i set them in start
both exist for a reason
when Start runs its safe to assume Awake has already run for all other active objects
Both awake and start only ever occurs once
so i setup stuff that only effects the current object on Awake, then i use Start for any startup logic that needs to reference and interact with other objects since at that point its safe to assume they have run awake
!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.
I need help, the button of previous is not worked.
https://gdl.space/jamuvezoji.cpp
quick question, lets say i want to refer to a filePath within the code to access a specific file inside the assets folder, how would i do that?
as i do not know where the possible end user has got the assets file actually stored
it does not work how you think
once you build the project there is no assets folder
im not that good with unity/c# yet but my autocorrect just stopped working now for some reason
is there any like
common issue of it not working
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
it was working fine yesterday
If it suddenly stopped chances are you need to regenerate project files
oh
so where would a file i need to deserialise go
if it was originally in the assets folder
what kinda file is it?
can i ask, im trying to lerp a rectangle 2d with this code
timeElapsed += Time.deltaTime;
if (timeElapsed < timeToReachTarget)
{
transform.position = Vector3.Lerp(transform.position, target.position, timeElapsed / 10f);
}
else
{
transform.position = target.position;
}
why does it reach the end position before the timelapsed reaches 10f?
how would i do that
.bin
make a field of type TextAsset
Go to your external tools menu and there's a button at the bottom to regenerate it
you will be able to click and drag the file into it, and access its data as byte[] or string
if TextAsset is not enough for your purposes you will want to look into the StreamingAssets folder
Put it after them in the hierarchy
How can i pick a point in the raycast if the ray is null? This not working.
if (Physics.Raycast(start.position, start.transform.forward, out hit, rayLenght))
{
if (hit.collider == null)
{
Vector3 pointInRay = start.position + new Vector3(0f,0f, rayLenght);
Debug.Log("You shooting nothing.");
}
else
{
Debug.Log("You hit something.");
}
i dont really understand im ngl
here is the context of where im using this
Well, your ray's direction is start.transform.forward. The pointInRay is assuming this object is always facing Vector3.forward
Your first if statement is checking if it hit something, add an else after that if it didnt instead of checking the collider
Oh, right, the collider cannot be null if the ray hit something anyway so it doesn't matter
if you are trying to include it in your game as jsut a file you would want to use
https://docs.unity3d.com/ScriptReference/TextAsset.html
or
https://docs.unity3d.com/ScriptReference/Application-streamingAssetsPath.html
Unless you've messed with the render layers, this would draw Panel on top of everything else in the canvas
for files to be included in a build, they must be referenced somehow, or in a addressable/assetBundle or be in the streaming assets path
so waht do i do bro😭
why does it nit destroy it when it touches something with the tag ground
Log collision.gameObject.tag before the if. See if you ever actually touch something tagged "Ground"
Does the object with this code have a non-trigger collider and rigidbody? And i assume the ground has a non-trigger collider?
Hey I'm pretty new to unity and working on a lobby/ relay system for practice/ to learn.
I'm making a host/lobby on one scene with a script attached, then trying to use SendHeartbeatPingAsync() in the Update method to keep the lobby active in another scene with the same script attached. When I create the lobby its there, but then disappears when i check again ~30s later
just a collider no rigidbody
Hello Guys
I Have a problem where i can't find the visual studio for mac.
Do you know how i can add it?
Needs a rigidbody for collision messages
but i dont want it to be affected by gravity
then disable gravity
oh ye lol
but at least one of the objects involved in the collision must have a rigidbody
is it enough if i set the gravity to 0?
What is the code to increase the opacity from 0 to 100 automatically?
.a = 1
just one letter? I get an error.
private void Update()
{
HandleLobbyHeartbeat();
}
private async void HandleLobbyHeartbeat()
{
if (hostLobby != null)
{
heartbeatTimer -= Time.deltaTime;
if (heartbeatTimer < 0f)
{
float heartbeatTimerMax = 15;
heartbeatTimer = heartbeatTimerMax;
await LobbyService.Instance.SendHeartbeatPingAsync(hostLobby.Id);
Debug.Log("Heartbeat ping");
}
}
}
public void StartHost()
{
NetworkManager.Singleton.StartHost();
NetworkManager.Singleton.SceneManager.LoadScene(gameplayScene, LoadSceneMode.Single);
CreateLobby();
}
private async void CreateLobby()
{
try
{
string lobbyName = "Lobby Name";
int maxPlayers = 8;
Lobby lobby = await LobbyService.Instance.CreateLobbyAsync(lobbyName, maxPlayers);
hostLobby = lobby;
Debug.Log("Created lobby " + lobby.Name + " " + lobby.MaxPlayers);
}
catch (LobbyServiceException e)
{
Debug.Log(e);
}
}
a = alfa?
how do u change these in code?
someone can help me?
https://gdl.space/elukevaqop.cpp
the previous does not worked
hi, i am searching desperately for a code to get the value of a variable of another gameobject, i tried several off youtube or in forums nothing worked
thx
Well still not doing what i want.. (line is a linerenderer)
Vector3 pointInSpace = laserStart.forward + new Vector3(0f,0f,laserLenght);
if (Physics.Raycast(laserStart.position, laserStart.forward, out laserHit, laserLenght))
{
if (laserHit.collider.CompareTag("FS/CON"))
{
line.SetPosition(0, laserStart.position);
line.SetPosition(1, laserHit.point);
}
}
else
{
line.SetPosition(0, laserStart.position);
line.SetPosition(1, pointInSpace);
}
Show what didn't work. Referencing other objects is basic Unity. Seriously doubt everything you found didn't work.
GameObject go = GameObject.Find("mainCharacter");
controllerScript cs = go.GetComponent<controllerScript>();
float thisObjectMove = cs.move;
this for exemple
Show this object in your hierarchy
"Does not worked" is not any information at all. You have to say what the problem actually is
@frosty hound i know i have to assign the script, but it didnt work
i cant drag and drop wether the script nor the object
Are you trying to drag a scene object onto a prefab
ye
so the prefab is the problem
so basicly i want that the bullet spawns at the players position
The fact that you're trying to drag an object that only exists when that particular scene is loaded onto an asset that always exists regardless of scene, is the problem
So spawn the bullet at the player's position
The prefab doesn't need to know the player's position to do this
just spawn it directly there
@polar acorn you mean just type instantiate in player
so when i build the project, nothing inside assets is included ?
so if i upload a textAsset to the Assets folder it will also not be included as well
generating the table during run time is also not an option
The text asset field will let you reference the data in the file like any other reference in unity
how do i get highlighted button color
So that will work for those purposes
You're instantiating it somewhere, right?
Ok, when I click the button it doesn't change image. And the button is linked to the script.
Just spawn it where you actually want it to be
Show the inspector of this object
but will the file be downloaded alongside the program
Show the inspector of this object. The one with the script on it
It will be included as part of the program and can be accessible through C#
ok lol
ok
thanks
It won't be a file you see with it, the text asset field will just give you direct access to the bytes
cloning prefab
If you have a serious need to bundle some loose files along with your game, that's what StreamingAssets is for
What are you trying to actually accomplish here?
Put this log inside of your for loop:
Debug.Log($"{gameObject.name} setting {background[i].name} to {i}=={index}: {i == index}", this);
and show what it prints when you click on the previous or next button
🇮🇩
Where did you put it
better
if you read this code, i am basically converting a table from my own computer from binary to an array of bytes which i am going to use as a hash table for heuristics, so i need the file. obviously it wont still be on that filePath for anyone else, so from what i understand i have to do something like this.
string filePath = "cornerHeuristics";
TextAsset cornerHeuristicsAsset = Resources.Load<TextAsset>(filePath);
byte[] cornerTable = cornerHeuristicsAsset.bytes;
But what do you mean when you say loop?
I mean the loop
the for loop
that you wrote
put it in there
@swift crag
Okay, so you just need to be able to include a blob of binary data in your game.
You don't have to use Resources.Load for this. You can just directly reference a TextAsset
i did
(which, confusingly, is used for both text and non-text data)
but the previous still not work
this is only one table. i have around 8 others i need to load also
Okay, cool, so, after this runs, the 4v4 object should be active. Can you show a screenshot of the 4v4 object while the game is playing, after this debug log shows that it's set to true
Then make a list of them!
or any of the other ones that are activated by it
So it's active
ik
Then what's the problem
You know, when I click the previous button it doesn't work
Looks like it's working just fine
I switched to 4v4 through the next
The log says 4v4 should be active
So then why did you show me it when that was never the issue
click on previous and show me what the logs print for that
It doesn't show any log
i dont really understand what you are talking about
Then nothing is calling that function
Or your list is empty
List<TextAsset>
you now have a list of TextAssets.
i dont get text asset
If you have nine very distinct tables, just make nine variables
still
It's an asset that stores text.
and it is included in the build
A Texture2D is an asset that stores an image. An AudioClip is an asset that stores audio.
the list is not empty
Of course it is. Assets would be useless if they weren't included in the build.
How do you know.
Log the size of the list outside the loop
why cant i just have the files included in the build themselves
But, as others have said, assets are not loose files. They're bundled into large archives.
Why do you need loose files?
i see
You just need the data, right?
yeah
If you actually need files, you can put things in StreamingAssets, which gets copied straight into the build directory
but it sounds to me like you just need a way to include some binary blobs in the game
i see
I know that's not the problem, there probably isn't a function that calls it
This is an ImageSwitcher. How do you know that this is the one you're calling the function on
How do you know that's not the problem
Log it
Prove it
if you knew what wasn't the problem, you wouldn't be here asking for help
please humor digiholic
log
it
log the length of the list
outside the loop
stop guessing
check
really need a !debug
I did that but it doesn't send any logs
Okay, so then that proves nothing is calling this function at all
now we have information
Nothing calls Previous
so do you know how to solve it pls?
Call Previous
a quick question, it is possible to detect something like this (between 1 and 16 can detect) but more than 16 it cannot detect?
if (remainingTime > 1 / 16) ?
I don't really know how because I think I did everything right
Where do you call Previous
or if (remainingTime > 1 = 16) ?
yes i see what you mean. it turns out i do actually only need one table to be added into the game. So, i have added cornerHeuristics.bin to the Resources folder, and will run this code:
string filePath = "cornerHeuristics";
TextAsset cornerHeuristicsAsset = Resources.Load<TextAsset>(filePath);
byte[] cornerTable = cornerHeuristicsAsset.bytes;
would it work ???
(after building)
Check if the time is greater than 1 and (&&) less than 16
if you obey the rules of Resources.Load, yes
this works if you have a TextAsset named "cornerHeuristics" in a folder named "Resources"
I am trying to make my game check to see if a folder exists and if not, then create said folder but, when i try to test run the scene in the editor it gives me this error:
"UnauthorizedAccessException: Access to the path 'C:\Users%username%\Documents\My Games\Transversal Platformer' is denied.
System.IO.FileSystem.CreateDirectory (System.String fullPath) (at <88e4733ac7bc4ae1b496735e6b83bbd3>:0)
System.IO.Directory.CreateDirectory (System.String path) (at <88e4733ac7bc4ae1b496735e6b83bbd3>:0)
BootupSave.Start () (at Assets/Scripts/BootupSave.cs:15)" and if i build it then it just does not make the folder, how do i make it create that folder?
my code for checking for the folder is this:
using System.Collections;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
public class BootupSave : MonoBehaviour
{
string savedir = @"C:\Users\%username%\Documents\My Games\Transversal Platformer";
// If directory does not exist, create it
void Start()
{
if (!Directory.Exists(savedir))
{
Directory.CreateDirectory(savedir);
}
}
// Update is called once per frame
void Update()
{
}
}
notice that you have that %username% thing in there
I don't know if that's going to get substituted for you
Also, this sticks out to me
from the error message: C:\Users%username%\...
that slash went missing.
There's some funky escaping going on here.
it is currently cornerHeuristic.bin
i am wondering if textAsset needs to have .txt extension, but you said before it handles text and non-text so it might not but idk
I would suggest just using Application.persistesntDataPath
that writes to AppData/LocalLow/CompanyName/ProductName/...
If Unity hasn't imported it as a TextAsset, yes, you'll need to change the extension to load it as a TextAsset
it is currently a binary file so how do i convert to a text asset. just add .bytes on the end instead of .bin ?
even if you don't want to use persistentDataPath for whatever reason, you shouldn't be hardcoding your path like that and should instead use Environment.GetFolderPath to get a special folder like the Documents folder
https://learn.microsoft.com/en-us/dotnet/api/system.environment.specialfolder
you don't convert anything
you just give the file an extension that Unity will import as a text asset
again, any of the extensions on the page I just linked will work
including .bytes
and how do i make it import it ?
by putting it in the Assets folder
as you would with literally any other asset
TextAsset isn't "special" in any way.
it works exactly like every other kind of asset you've ever used
here is my .bin file alongside other TextAssets
does it need to be in the same format ?
i'm not sending you random links for fun
you can also change the extension after you put it in Assets
you'll just need to do that outside of unity, since Unity doesn't let you change the extension
yeah ok let me try that
They're intending to use Resources.Load , apparently.
Ah I would use text asset or addressables or streaming assets over it
Text asset or streaming assets feel most suitable for that case
over what? you just named all of the possibilities :p
Resources
a TextAsset is a TextAsset, whether or not it's in Resources
Text asset with direct ref before best for just building in a binary blob
Why does my shooting code run slower when I move the player than when I keep the player still?
void Update()
{
frameNormal++; ;
if (ControlsSwitch.isMouse)
{
if (Input.GetMouseButton(0)) // If LMB is pressed down
{
if (PlayerScript.playerLevel == 0)
{
if (frameNormal > baseShootSpeed) // If <baseShootSpeed> frames have passed
{
Instantiate(bulletObject, transform.position, Quaternion.identity); // Create bullet
frameNormal = 0;
}
}
}
}
else
{
if (Input.GetButton("space")) // If Space is pressed down
{
if (PlayerScript.playerLevel == 0)
{
if (frameNormal > baseShootSpeed) // If <baseShootSpeed> frames have passed
{
Instantiate(bulletObject, transform.position, Quaternion.identity); // Create bullet
frameNormal = 0;
}
}
}
}
if (frameNormal > baseShootSpeed + 16)
{
frameNormal = baseShootSpeed + 1; // Make sure no overflow can happen
}
}
because you're counting frames
I presume the game is running slower when you're moving, for whatever reason
don't count frames
use Time.deltaTime to determine how long the last frame took, and use that to determine when you're allowed to fire
I assume in frameNormal I multiply it with timedelta first, then do +1?
Use time stamps to make it relative to time rather than frames.
I do not follow.
timeSinceShot += Time.deltaTime;
if (timeSinceShot >= shotDelay) {
// shooting is possible
timeSinceShot = 0;
}
Neither do I, I'm not familiar with the complex terminology.
Ah thanks
if(next < Time.time)
{
next = Time.time + delay;
...
}```Does not account for poor frame rates.
this is also a good idea
I prefer to count up like this to properly handle multiple shots per frame
Hm, still shoots slower while moving...
float delay;
void Update() {
delay -= Time.deltaTime;
delay = Mathf.Max(0, delay);
if (wantsToShoot) {
while (delay <= 0) {
// fire bullet
delay += shootDelay;
}
}
}
then show us:
- the entire script that your excerpt was from
- your movement code, if it's in another script
Does it feel slower or is definitely slower?
Definitely slower. In the left menu, it shows significantly more bullets while not moving than while moving.
One sec, lemme upload it
you'll have to remember that we have no idea what a "left menu" is
Bullet: https://hatebin.com/cozqhongey
Movement: https://hatebin.com/jhlbskqcaj
This one
that's the hierarchy
also, your code has barely changed
you're still counting frames
frameNormal++;
if (frameNormal > baseShootSpeed + 16)
{
frameNormal = baseShootSpeed + Time.deltaTime; // Make sure no overflow can happen
}
this doesn't make any sense to me
I make it so it only shoots a bullet every 16 frames
I wrote the code a while ago btw
don't do that
Right, it was to make sure it doesn't overflow, thus the 16
don't try to write any more code until you've read this
Apologies
you have a severe misunderstanding of how all of this works and you need to correct it now
you don't need to go through all of the examples, but at least get through the "Variable frame rate management" section
It's pretty bad to tie to frames unless you are locked frame rate and are well optimized enough it is rock solid even on rubbish hardware on a engine designed for that. So not unity
Just count accumulation of deltaTime
So this? frameNormal += Time.deltaTime;
well, yes, because the rest of your code is still probably waiting for that variable to reach 16
you can't just change one line and then hope everything is fine now
you need to think about the implications of your changes
And I am here asking for help to figure out why it doesn't work like I want it to. If I knew exactly what was wrong, I wouldn't be asking.
Then show me what your code looks like now.
I can't guess what you've done.
well, I can, but it's not very productive (:
how can i build my project so that it can only open in the 16:9 aspect ratio?
https://hatebin.com/cbvgwtfqbk
I also tried changing this:
if (timeSinceShot > baseShootSpeed + 16)
{
timeSinceShot = baseShootSpeed + Time.deltaTime; // Make sure no overflow can happen
}
to this
if (timeSinceShot > baseShootSpeed + 16)
{
timeSinceShot = 0; // Make sure no overflow can happen
}
```But that also did not make it work again.
Look at every line that still talks about "frames"
all of these lines are either:
- wrong
- using a value you need to change
baseShootSpeed should definitely not still be 16
that would mean you shoot once every 16 seconds
the 16 value here is also now incorrect. If you're really worried about the float overflowing, I guess you could do...
timeSinceShot = Mathf.Min(timeSinceShot, baseShootSpeed);
This would be how I'd fire given your codecs private float next; public float delay; private void Update() { if(!(ControlSwitch.isMouse ? Input.GetMouseButton(0) : Input.GetButton("space"))) return; if(PlayerScript.playerLevel > 0) return; float current = Time.time; if(current < next) return; next = current + delay; Instantiate(bulletObject, transform.position, Quaternion.identity); }
you got to think in time not frames, like think fast you want it to fire, like a shot say 0.2 of a second or something like that
Store the time, not the frames. It's the only unit of measure that exists . . .
does changing timescale make update run slower
no @stuck palm
!docs timeScale
It messes with delta time and time dot time though .
There's https://docs.unity3d.com/ScriptReference/Time-unscaledTime.html to make up for it.
Update is based on your framerate, that will differ based on your machine, if you got vsync on or off, etc timescale just scales deltaTime and time
You'd use the unscaled varients if you're working with time and aren't wanting time scale to effect certain behaviors.
Yea I'm just gonna give up.
its literally 2 fields a Update method and a few lines of code
if you refuse to try, then you will fail
I would strongly suggest following some tutorials on !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
a great example is for UI animations
you probably don't want those to stop when the timescale is set to zero..
are player input events affected by timescale
no
are coroutines affected by timescale?
it effects Time.time, Time.deltaTime, Time.fixedDeltaTime, WaitForSeconds in coroutines and the fixed update
it depends
everything that happens once per frame continues to happen once per frame
if you are using deltaTime in them, or time, or WaitForSeconds yes
if not not
its not touching the framerate so updates happen at the same rate they normally due, and that includes yielding frames in coroutines
I'm sorry if this sounds negative, but I'm here to learn interactively. A static text can't respond if I tell it that its approach doesn't apply to me. I really hoped for some help, but it's already pretty late and I'm about to tear my hair out, so I just hope that whenever I retry, I'm not just pointed to the 8tth redirect to "THE" help forum, but rather get an answer that I can work with. I greatly appreciate your time though, thanks.
People here aren't going to write all of your code for you. You need to put some effort in to reason about your problems.
You can yield using https://docs.unity3d.com/ScriptReference/WaitForSecondsRealtime.html to not be relative to the time scale. Pretty sure most stuff revolving time in Unity has an unscaled time variant.
My impression is that you're making the minimum possible change and then hoping the game will start working right.
That ain't going to cut it.
Tutorials are there to help you build a baseline understanding. They aren't going to be the only thing you ever learn from
anyone willing to help wants to be met half way, people did a lot of hinting in directions to look at that would have solved the problem
Yea, because I'm basically forced to do it that way, because I only get a vague pointing into an overly complicatedly worded site instead of "On line X, Y, and Z you forgot to do A and B", which I can learn more from than from trying to smash my head against a keyboard for an hour. Not everyone has the able-mindedness to immediately comprehend that stuff. Again, I do appreciate you putting your time in.
If you don't understand a thing, ask about it
don't just shrug and hope it's unimportant
I did, and was pointed to a site I understood even less.
No, you didn't ask me questions.
You posted code, asked about a single-line change, and then declared you're giving up
@swift crag Hey thank you for your help earlier this day! (I was the guy with the ecg). I looked into the linerenderer and while searching for this i found the trailrenderer. I played arround with both and found the trailrenderer to actually work quite fine for the project. However there are 2 new problems presenting themselfs to me now. 1. i have to somehow generate a trail for an object only moving up and down that goes to the left 2. i somehow have to limit the trails lenght only on one axis (so it always ends at the same place even when the atached object goes up and down constantly). What i tried so far: 1. make the object move to the right instead of standing still -> only works one time or will look very ugly if reset to the left side again; moving the cam with object constantly to the right -> will work in 2d, but if tried to apply it in an object in 3d (like a monitor) wont work 2. no idea how to fix it and didnt find anything in stack overflow / youtube. Anyone has any idea how to do that?
I am trying to help you here, but you've gotta meet me halfway.
I knew I had to use "Time.deltaTime", but I have no idea where, and once that site got put up, I then had to experiment around with not just "where", but also which subclass (or whatever it's called), trying to understand the graphics, etc.
Then ASK.
I can't really do that if I was already at the end of my wits.
I can't read your mind.
if you're at your wits' end, you need to take a break
because it's incredibly hard to learn anything when you're burned out and tired
Which I am currently.
But yea, again I do appreciate you taking the time. I hope you have a great rest of your night.
you could have the entire trail renderer fade out before the next wave appears
that way, the jump never happens in the first place
alternatively, use two line renderers
one would fade out as the next one started drawing
oh yeah... wow that was way too simple. i feel stupid now
i hadn't thought of it earlier :p
however, the 2. problem is still there
point 2 sounds like you just need to switch to local space
I think the default is world space, where [0,0,0] means "center of the world"
when you switch to using local space, [0,0,0] means "my position"
i dont really follow here
what i was trying to say is: i can define a lenght for the trail, however if up/down movement is high, the line will be shorter (if only left/right size counts) and if up/down movement is low, the line will be longer
Ah, I get it
i want to add "abilities" to a list, all have different code but are an ability. i tried it with interface and with just adding a class, but i can't add it to the list in the inspector
you're talking about the trailrenderer
there seems do be no way of limiting the trailrenderers lenghts only in one axis
That's a big strike against using that.
I thought you were having problems with the line appearing in the wrong place when you moved the display around
Although...doesn't the trail renderer use time, not length?
maybe some setting i have not seen... but for me it seems to use length
Unity can't serialize an interface type.
You can probably just use an abstract class here.
public abstract class Ability : MonoBehaviour {
public abstract bool CanUse();
public abstract void Activate();
}
sort of like this
Since Ability derives from MonoBehaviour, it's a unity object, and thus it can be serialized
yeah unless its SerilizeReference you cant Serilize a interface abstract class is the way with the most easy to do something similar
my code is set to load one scene, but it only seems to load the current scene its in right now. no idea why it does this
(and [SerializeReference] requires you bring your own inspector UI)
oh wait, i think i know why it seems to use length for me. When i tested it the overall speed was the same, but actually the speed of one axis should stay the same without considering the other axis.
if you implement what I suggested this morning, your code will look something like this
void Update() {
float x = Time.time % 1;
float y = CalculateEKG(Time.time % 1);
trailRenderer.transform.localPosition = new Vector3(x, y, 0);
}
x is just going from 0 to 1 over and over, once per second
% is the remainder operator, if you've never seen that
it gives you the part that's left over after division
i also find its fragile as well, had what i thought was a good usecase and ended up junking it
is it possible to add scripts to a list that are not attached to any object? just the script itself?
Not with a MonoBehaviour.
sure, you can still do regular C# stuff
how then
just makes instances of a regular old class that is not a MonoBehaviour or ScriptableObject
so yeah, two options
you can just serialize an ordinary C# class, like this one
[System.Serializable]
public class Foo {
public int x;
public float y;
}
Note that this would not automatically let you do polymorphism
public abstract class Ability {
public abstract void Activate();
}
public class Explode : Ability {
public override void Activate() {
Debug.Log("An earth-shattering kaboom!");
}
}
you wouldn't be able to serialize an Ability and wind up putting an Explode in there in the inspector
the abstract class would be the fastest way to do what you want if you can work with the limitation if not implementing multiple interfaces at once
I'll get back to that in a moment
The other option is ScriptableObjects. These allow you to create instances of unity objects and store them as assets.
@swift crag thanks again. You were really helpful!
i am confused.
So you could serialize an Ability and then drag any ability asset into the field.
public abstract class Ability : ScriptableObject {
public abstract void Activate();
}
[CreateAssetMenu(fileName = "New Explode Ability", menuName = "Explode")]
public class Explode : Ability {
public override void Activate() {
Debug.Log("An earth-shattering kaboom!");
}
}
about what, exactly?
or my I can't be bothered with OOP right now way:
public abstract class Ability : ScriptableObject
{
public abstract void Activate();
[SerializedField] private ExplodeComponent explodeData;
public ExplodeComponent ExplodeData => explodeData;
public class ExplodeComponent()
{
//should have private setters too but im lazy
public bool enabled = false;
public float radius;
}
}
wot
Component check, if set then apply it. Beats digging yourself a hole when you want to say have your lazer class have some explosion at the end of the hit
wait i am trying it out
few comparison checks won't hurt and stuff like these systems of classes are easy to make hundreds of if you don't design it beforehand
Note that, if you do this, multiple people could be referencing the exact same asset
you would not want to store data that changes in there
But it would be very reasonable to store fixed data.
[CreateAssetMenu(fileName = "New Explode Ability", menuName = "Explode")]
public class Explode : Ability {
[SerializeField] float damage;
[SerializeField] float radius;
public override void Activate() {
Debug.Log("An earth-shattering kaboom!");
}
}
you could create multiple Explode assets and give them different values
I don't think it's a huge problem for abilities to be MonoBehaviours that you attach to each character, though.
That makes it easy to keep track of stuff like cooldowns (and any other data that needs to be remembered)
each character has their own ability components
but my game is mod based, i want to just drag and drop ability presets into a list
"mod based"?
yes, if you create a variation of a unit (strategy game) in the game as a mod you just add abilities to it, with fixed values at default
have you played tabs (totally accurate battle simulator) ? they have a unit creator where you can add abilities
I'd have to think about that for a bit.
what you said works tho
just keep this in mind
you'll need to store per-unit data somewhere
the scriptable object has values
(like how long their Punch ability needs to wait until it's off its cooldown)
if ten units all reference the same scriptable object, then they'll all share the exact same object reference
One option could be to Instantiate the scriptable objects when you spawn the units into the game world
Instantiate copies any Unity object. It's not just for MonoBehaviours and GameObjects
uhm that wouild be performace intensive in a strategy game
it'll make a little garbage
doesn't sound like an issue to me, since you do it just once per ability
[SerializeField] List<Ability> abilityTemplates;
private List<Ability> abilities = new();
void Awake() {
foreach (var ability in abilityTemplates)
abilities.Add(Instasntiate(ability));
}
something like this
now each unit has its own ability objects
but if i just want the abilities all to have the same values it should work like this?
If Unit A uses an ability, should it go on cooldown for every single unit that uses the ability?
That's what I'm talking about.
ah
New to Unity and trying to setup the Unity extensions in VSCode (Unity & Unity Code Snippets). I've got .NET installed and restarted but now I'm getting this output
2024-01-26 19:04:44.266 [error] (Z:\Unity\Projects\Floppy Birb\Assembly-CSharp.csproj): SDK Resolver Failure: "The SDK resolver "Microsoft.DotNet.MSBuildWorkloadSdkResolver" failed while attempting to resolve the SDK "Microsoft.NET.Sdk". Exception: "System.IO.FileNotFoundException: Could not load file or assembly 'System.Collections.Immutable, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
File name: 'System.Collections.Immutable, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
at Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.CachingWorkloadResolver.Resolve(String sdkReferenceName, String dotnetRootPath, String sdkVersion, String userProfileDir, String globalJsonPath)
at Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.WorkloadSdkResolver.Resolve(SdkReference sdkReference, SdkResolverContext resolverContext, SdkResultFactory factory)
at Microsoft.Build.BackEnd.SdkResolution.SdkResolverService.TryResolveSdkUsingSpecifiedResolvers(IList`1 resolvers, Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive, Boolean isRunningInVisualStudio, SdkResult& sdkResult, IEnumerable`1& errors, IEnumerable`1& warnings)""
2024-01-26 19:04:44.318 [error] Failed to load project 'Z:\Unity\Projects\Floppy Birb\Assembly-CSharp.csproj'. One or more errors occurred. (SDK Resolver Failure: "The SDK resolver "Microsoft.DotNet.MSBuildWorkloadSdkResolver" failed while attempting to resolve the SDK "Microsoft.NET.Sdk". Exception: "System.IO.FileNotFoundException: Could not load file or assembly 'System.Collections.Immutable, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
File name: 'System.Collections.Immutable, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
at Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.CachingWorkloadResolver.Resolve(String sdkReferenceName, String dotnetRootPath, String sdkVersion, String userProfileDir, String globalJsonPath)
at Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.WorkloadSdkResolver.Resolve(SdkReference sdkReference, SdkResolverContext resolverContext, SdkResultFactory factory)
at Microsoft.Build.BackEnd.SdkResolution.SdkResolverService.TryResolveSdkUsingSpecifiedResolvers(IList`1 resolvers, Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive, Boolean isRunningInVisualStudio, SdkResult& sdkResult, IEnumerable`1& errors, IEnumerable`1& warnings)"" Z:\Unity\Projects\Floppy Birb\Assembly-CSharp.csproj)
2024-01-26 19:04:44.321 [info] Project system initialization finished. 0 project(s) are loaded, and 1 failed to load.
Sorry if this is the wrong channel to post this in
Just, quick question, what does this mean? Is it worth trying to fix? (I'm trying to make entering a trigger play an animation)
just slap new onto the variable declaration like the warning suggests
it's happening because Component has an old deprecated member named collider that would have referenced its collider. it's no longer in use though so if you want to create a variable with that same name you just have to hide the old deprecated one with that new modifier
Or use the C# naming conventions (pinned to #archived-code-general) and name private variables _collider and public Collider and don't have naming conficts that way.
guys I want to create a objective UI that has a method UpdateObjective(), but I'm not sure how to call it from another game object
get a reference to it and call it. or subscribe that method to some event
you clearly have multiple copies of it in different places. delete the old copies
just ask your question here
How to make "equals" auto align in a raw in visual studio?
Would probably need to find a setting in your ide/code editor.
Make a thread
why is it not accepting the OnCollisionStay2D? i haven't had this problem before
did you read the error?
yah, i don't understand what its telling me
you have the wrong parameter type
it also looks like you have an unconfigured !IDE so you better get that sorted 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Is that munally typed "space"? I used visual studio a while ago.But still dont know how does some ppl write them
I don't know if there's any setting to do it automatically, but using Tab would usually standardize the spacing.
Honestly, I'm not a big fan of aligning things like that. Feels like a waste of time and hindrance for future edits.
Dose anyone know how to fix this error?
start by getting your !IDE configured 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
ok i did all the steps
do you see a red underline on line 27 now?
ya but now its asking me to sign in, i made a new account but its still asking me to do a capcha
Please don't make suggestions until they confirm their IDE is configured
visual studio now its asking me to sign in, i made a new account but its still asking me to do a capcha
I don't know why that matters to me? Do the capcha if that's what's blocking you
i did like 10 times
i dont know if you know how to fix it?
I don't know why you've installed VS when you were originally using VS Code?
Just configure VS Code?
Oh
How could I find the position for the 2nd card, knowing it'd always be 0.6m away, without using transform.right? (so only with position/rotation)
Create a vector representing transform.right from position and rotation and use that. At which point you might as well use transform.right.😅
like what's the use case here
probably a lot of ways to resolve what you're trying to do
its really long to explain
think in terms of UI if anything
You guys think this would work?
Vector3 posOffset = Vector3.right * 0.6f;
Quaternion rot = Quaternion.Euler(Rotation);
Vector3 secondCardPosition = firstCard.position + rot * offsetVector;
i cant try it and see rn
is this like error or something?
please anyone explain
Anyone with unity experience wanna give me a quick hand with one of Kenney's character's animation's import settings?
I'm new to Unity and after having followed 3 tutorials decided to give my own shot at my own project.
I'm using Kenney's mini-arena asset and I've imported the character-soldier model, so far I've set up the animator controller with triggers for each animation that are triggered by the PlayerMovement script, but it looks like the animations aren't fully looping through and instead being restarted every frame (and also finishing their loop once I do let go of the inputkey)
video for added clarity
Screwdriver indicates that there are options where you can change the code
so it doesnt mean error?
cause im stressed out after i saw that
No, hover over it/click on it and see what it says
ok, but what about the yellow thing?
Use boolean logic for looping clips
triggers for one-offs
I tried that a second ago but it didnt seem to work, let me try it again and I'll report back to you
It usually shows what lines where edited recently.
still want a statemachine even if it seems like the animator handles it all (it doesn't)
For errors, warning, you should pay attention to underlines in code and the console in your ide and unity.
Still not functioning as it should, I suspect it might be something I didnt do in the import settings of the character model
Your walking animation keeps resetting but it should be playing out completely unless interupted
Yeah exactly
Also for reference this is Kenney's documentation for importing chars and animations, but the only thing I've been able to achieve from this is enabling "loop time"
I couldnt set it as humanoid in the rig tab since it doesn't have enough bones according to unity, and for the rest besides the animator controller stuff, I wasnt able to find the settings like "Root Transform Rotation" etc
perhaps play around with the blend times to see if it's getting interupted early
Could u elaborate on what you mean?
Also for clarity, when I stop pressing the input key, it does finish the full animation loop
but whilst holding the input key it keeps refiring the animation like you've stated
and for further clarity the animation import settings for the character's walk animation
yeah, maybe adjust your code and make sure stuff isn't being flipped on and off even if it's all in a single frame
and to secure the logic even more, make some states and check what you're in each frame instead of relying specifically on that frame's input
Quick question, what do i use to turn the particle system on? (eg. animator.enabled) cause this doesn't work
what's the underline
What's weird is that while looking at the animator in the video it doesnt look like anything is flip flopping like that, could it be related to this highlighted area being too narrow?
that's what I was referring to, but I'd suggest fixing up the code too
For sure, the code was just quickly thrown together to test out if I could get the animations to work, like I said it's my first time going tutorial free on unity 😅
i downloaded the wrong program the whole time ;-;
it shouldnt be microsoft visual studio 2022
it should be vs code
no wonder i dont understand a single thing
For some reason, whenever my gameObject touches a certain layer, it doesn't detect it. https://pastecode.io/s/jj0ge2ez
i dk what to say about the code
if (Other.gameObject.layer == 0){
Falling = false;
Rotating = false;
Left = false;
Right = false;
}
```no idea why when layer==0 spawn is not setted
Visual studio is arguably better though.
btw this is quite hard to read
if (Input.GetKeyDown(KeyCode.X)) {
if (Rotating == true)
{transform.Rotate (0, 0, 90);
if (Left == false)
{transform.Translate (-1f, 0, 0);}
if (Right == false)
{transform.Translate (1f, 0, 0);}
}
}
```i dont want to simulate a stack in my brain to get the scope back
took me way to much time to understand it was nested if statements 
what is noticeable between 2019 and 2022 ?
i am using 2019 rn because i had some weird issues when trying to setup 2022, i am still wondering if its worth the change
Navmesh changed from built-in to navigation package as well as functional changes. Can't think of anything else, aside from added features.🤔
Maybe changes in specific packages, like ECS. But since they were experimental/preview anyway, I wouldn't count that.
I mean, in terms of positive changes there were a lot. From stability and performance, to improvements in the render pipelines, shader graph, vfx graph, etc...
I have no idea how debugs.log works
A thousand messages come out every minute, you can delay the game, right?
but can it cause the game or nothing?
if you call it somewhere where the code is called every frame (like Update), you have to expect to have a lot of message very fast
wdym with "cause the game" ?
Debug methods, like any methods, can make the game lag if there are to much
but with debuglog you can still have multiple of them every frame and it will be fine (for debugging purposes)
So when there are thousands of messages the game can have delays
Sorry for that question, although I have been new for 1 month and I am learning.
there is no need to keep old debug logs when you dont need them
Perfect, that's what I wanted to know :D
if (remainingTime == 1) Is it not possible to detect the same number?
The problem is that it detects less than 1 and I want to detect the same number
it is very recommended to use < or > with floats, because most of the time it wont be a exact "int" number
example:
instead of 5 it will be 4.999815
Mathf.RoundInt? 
depends of the case
Still better to use greater or lesser comparisons imo.
idk if this occurs for simple math like
float a = 1;
float b = 2;
a + b // 3 ?
I'll try to understand, I'm too slow to understand LoL.
finally i did it, i made my first ever 2d topdown movement
how do you track remainingTime ?
It's a stopwatch
time is subtracted*
so my guess is that its updating each frame, but because you are using == remainingTime has to be 1, but because frames are inconsistent, it would be numbers like 0.956 then 0.99 1.06, ...
so Unity wont have remainingTime == 1
It doesn't work but I'll use that anyway ;(
@queen adder Please don't post random stuff without context
is it possible to use function on button which has more than 1 attribute? when i try do that buttons dont see the functions
your function can have multiples attribute
how to apply it on button then
[A,B,C,...]
your function()
Button will expect a specific signature, if you want to run anything else you can call another method inside
alright thank you
was making a health script and this error came up i have no clue how to fix it
ok i really should of said i have no clue why it has an error cause as far as i can tell i did things right
excuse me ,Suppose there are 100 types of enemies. How would you organize and allocate scripts for them?
Scriptable objects
same can also be done with items
!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.
https://gdl.space/ozibagagaf.cs This is a script for a bat. The bat has a trigger col and the enemy has a normal collider and has the tag "Enemy". I swear I checked the spelling. Why is my bat not detecting the enemy? The debug.log i set up is never getting called
I have just started using unity and I wanted to create a collectable item, I used this code to do it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collectables : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D collision)
{
PLayer player = collision.GetComponent<PLayer>();
if(player)
{
player.Seed1++;
Destory(this.gameObject);
}
}
}
Destroy is misspelled
oh, thanks i feel stupid
Haha dw
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
can anyone help me with this?
UnassignedReferenceException: The variable reload of SingelShot has not been assigned.
You probably need to assign the reload variable of the SingelShot script in the inspector.
UnityEngine.Object.get_name () (at <f7237cf7abef49bfbb552d7eb076e422>:0)
SingelShot.Reload () (at Assets/Scripts/SingelShot.cs:76)
SingelShot.Update () (at Assets/Scripts/SingelShot.cs:51)
does anyone know what this means
Assign the variable, read the messge
but i did
it might be getting disabled at start, or you didn’t set it up properly
duplicate instances
btw
public void Method(){
if(some condition){
Debug.Log("Hello world");
}
}
```what are the two possible reasons why you dont see Hello world
but doesn’t the method get called if the trigger collider collides?
in my case*
My tags are set up corectly and I am using the CompareTag
first thing is to check if your method called
okay I'll add another debug there
private void OnTriggerEnter(Collider other)
{
Debug.Log("Ontrigger called");
if (other.CompareTag("Enemy"))
{
attacking = true;
Debug.Log("Enemy detected");
}
}
The method isnt getting called
no debug messages
but my bat has a trigger collider
does the enemy has rb and collider
and follow the guides
no just a collider
you need rb
Thanks, I don’t know how i forgot that. 🤦🏻♂️
does making a variable nullable interfer wit hshowing the var in the inspector ?
i cant find a way to make a variable show, the only differences with the other vars i have is that its nullable
unity wont serialize nullable afaik
:(
nullable is a wrapper you can copy the source code
i remember there are alternatives but i forgot, maybe search nullable in channel history
How do you debug floats and check their current value in the logs?
by logging the float....
Debug.Log(your float)
That would probably give me the value of one frame
Is there any way to see if the value is changing or not
you could make it public or seralize it to see it in the editor
ah yeah
hello, I was wondering if someone could help me.
I'm trying to create a trigger that only triggers when the gameobject of the player is fully inside of it.
However, it does not work completely. Unity Engine understands when the player exitst the collider fully and gives me the debug. But it does not register the player when it is fully encapsulated by the trigger collider.
on trigger enter is called once right after they touch, so obviously the collider is not inside another collider yet
Compare to previous log🪄
what method would you suggest I use?
by continously checking
thanks
so I did some checking and
the float does reduces with delta time
but It stays on that value
It doesn't stores 1 after reaching 0
Why this isnt working?
hover on the line to read the message
and please store the collider in class member instead of GetXXX.GetXXX.GetXXX.....
Could not convert from 'method group' to 'UnityEngine.Collider'
you are missing something, how you call method?
i pluged my prefab into gorillaPrefab in editor, so i dont think i missed anythink, and the physics thing is on start
oh sorry, i forgot to add ()
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
I changed my visual studio code preference to open in visual studio 2022, and after this the scripts became invalid, then after closing and relaunching my unity project, it prompted me to open in safe mode and now I'm getting this error, any help would be great, thanks
Do you use visual scripting?
Yes, I used it for my previous scripts
Then I changed the preferred visual studio from 2019 to 2022
Then my scripts became invalid, then I re started the program and this happened
but do you use visual scripting in this project? Visual scripting, not Visual Studio
Oh, I don't know, I don't think so
https://gyazo.com/4dd419cac93ae27186cfab5c43b79cee guys why do i get type mismatch when i try to drag the playergameobject into the [SerializedField] Gameobject ?
Then you can uninstall the package
The data type you have used for the serialize field doesn't match the data type of the item you dragged in
but they're both gameobjects
Like in the script i typed [SerializeField] GameObject name
oh I see thank you nitku
and then i'm trying to drag and drop player object
oh
Do you have a rigidbody2d component added to the player
ye i do
maybe put that in?
That definitely won’t work
ok sorry
Restart your editor @late bobcat
You can't drag in objects from the scene to prefabs
^ @late bobcat
oh i tought component was different from object
how should i do that then?
grab it from the script or something?
assign the reference when the enemy is spawned
@keen dew I just opened my project and everything is gone, there is nothing but the main camera. No errors though
I went into package manager and deleted visual scripting
Open your scene
📃 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.
did my own dialogue/cutscene system based on tutorials, added bunch of stuff and combine everything in one item, but when dialogue starts it says that queue is empty and giving me default stuff in dialogue that is set in editor, what should i do?
https://hatebin.com/gnunuwiiuy
(P.S. ignore In game console plugin, it gives me this error every time after compilation while playing)
What calls StartDialogue
lemme see, i almost forgot
Okay, and none of the objects involved are prefabs you might have referenced somewhere instead of an object in the scene?
i forgot to mention
it actually worked before i put everything in DialogueItem
(you can see commented stuff in "Dialogue")
Ah, I see now. You're calling Dequeue over and over and expecting it to get the same thing. Once something's dequeued it's removed from the list. Dequeue it once at the top of the function and store it in a variable. Then reuse it in all of those places
okay ill try, thanks
You can use Peek() instead.
as the name implies, it lets you peek at the head of the queue
string a = "o";
string b = a + "k";
string c = b + " ";
string d = c + "b";
string e + d + "o";
// user was advised this joke isn't funny
I agree though -- even if you still use Peek()!
var currentDialogue = whatever.Peek();
You are right! Definitely just dequeue it once here.
I misread it and thought Dequeue() was being used in two different methods
it really helped, thank you!
i did this
if (dItem.Count == 0) { EndDialogue(); Debug.LogError("No dialogue items was found"); return; }
var stuff = dItem.Dequeue();
string sentence = stuff.sentence;
dialogueText.text = sentence;
// rest of code
still, thank you guys for help
I've been stuck for hours now. I'm trying to create a trigger in which the player object needs to be enveloped by the trigger collision box. That didn't work. Now i'm trying to have two triggers in an empty gameobject. Both triggers need to be actively touched by the player, however nothing happens. I can't even get one trigger to work.
public bool child1Inside;
public bool child2Inside;
private void OnTriggerEnter(Collider other)
{
Debug.Log("Enter");
if(other.gameObject.CompareTag("Player"))
{
if (other.transform.IsChildOf(transform))
{
if (other.name == "UpperT")
{
child1Inside = true;
}
else if (other.name == "LowerT")
{
child2Inside = true;
}
CheckDualChildTrigger();
}
}
}
private void OnTriggerExit(Collider other)
{
Debug.Log("Exit");
if (other.CompareTag("Player"))
{
if (other.transform.IsChildOf(transform))
{
if (other.name == "UpperT")
{
child1Inside = false;
}
else if (other.name == "LowerT")
{
child2Inside = false;
}
CheckDualChildTrigger();
}
}
}
private void CheckDualChildTrigger()
{
if(child1Inside || child2Inside == true)
{
Debug.Log("Both Inside");
}
}
}
define "can't even get one trigger to work"
as in, you don't even get "Enter" messages?
i don't even get the enter message
Walk through these steps
I used to have a ton of trouble with physics messages
there are a few different things that all have to be correct, or nothing happens
thanks! I'll go through them now
if (other.transform.IsChildOf(transform))
This seems weird to me, though..
This implies you're trying to overlap with colliders that are children of yourself
I got desperate and asked ChatGPT for some help. I asked him about it but his explanations weren't really sinking in.
ok, i managed to get the Enter and exit messages
Did you read the page I linked you to
It explains each thing you need to do.
if (other.transform.IsChildOf(transform))
I'm still very confused by this line.
Now i'm trying to have two triggers in an empty gameobject. Both triggers need to be actively touched by the player
I don't see why you're checking if the player is a child of the empty game object.
that line is written by ChatGPT, I think he told me that it is to check that a child object is being touched by the player.
well there's your problem
i would advise against using a spam generator to write your code
This code is also checking if other has the "Player" tag, but is then checking if the other object is named "UpperT" or "LowerT"
That implies that "UpperT" and "LowerT" are two colliders on the player
You can't tell which of your own colliders caused a trigger message to be sent.
I presume you're trying to detect which of the two colliders on the empty game object was overlapped
You can't do that if they're both on the same game object.
You could detect the overlap on the player side (since you know exactly which Collider you hit)
I'm unclear on what your end-goal is here, though.
Explain what you want the game to do.
not "detect when two colliders overlap"
The idea is that the player moves the black box up and down. At certain heights are spots where he needs to stop the box but the height is specific so it needs to be within a certain area. A large trigger box didn't work for some reason so I'm trying to use 2 triggers that both need to be touched at the same time.
The two grey boxes are the triggers
okay, I think using two trigger colliders makes sense here
here's what I'd do
make a component called PlayerSensor. It will look something like this
public class PlayerSensor : MonoBehaviour {
public bool playerDetected = false;
void OnTriggerEnter(Collider collider) {
// decide if the collider is from the player
playerDetected = true;
}
void OnTriggerEnter(Collider collider) {
// decide if the collider is from the player
playerDetected = false;
}
}
Create a game object with:
- PlayerSensor
- a trigger collider
This will be a single sensor. If you want to have two colliders, just make another sensor.
Now you need something that can decide if all of the sensors are detecting the player at the same time.
public class SensorList : MonoBehaviour {
[SerializeField] List<PlayerSensor> sensors;
void Update() {
bool success = true;
foreach (var sensor in sensors) {
if (!sensor.playerDetected) {
success = false;
break;
}
}
if (success) {
// do something. every sensor is active
}
}
}
Drag the sensor objects into the Sensors list
So your hierarchy might wind up looking like this:
- Puzzle <- has a SensorList
- Sensor <- has a PlayerSensor and a BoxCollider
- Sensor <- has a PlayerSensor and a BoxCollider
- Sensor <- has a PlayerSensor and a BoxCollider
this would require you to overlap all three Sensors at once
Thanks! I'll start working on it! Thanks for all your help!
no problem (:
this separates the duties out into two classes
in the future, you could even use this to combine many different kinds of "sensors"
public abstract class Sensor : MonoBehaviour {
public abstract bool IsSatisfied();
}
public abstract class ColliderSensor : Sensor {
[SerializeField] bool wantsOverlap;
// all of the stuff from above
public override bool IsSatisfied() {
return wantsOverlap == playerDetected;
}
}
if wantsOverlap is false, the sensor reports true when you aren't overlapping it
and then you could have other things, like a RaycastSensor that shoots a raycast to decide if it's happy
etc.
SensorList doesn't have to worry about how its sensors work
Awesome! Defenitely looking into this as well!
So I've got VS Code up for my scripting, but I'm not getting autocompletes for Unity-specific classes