#💻┃code-beginner
1 messages · Page 28 of 1
Share the whole code.
Gotcha, which website do you perfer
And the error too.
Any would do.
!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.
"Assets\Scripts\DiscoFloorSpeed.cs(13,26): error CS1061: 'Tilemap' does not contain a definition for 'AddTileAnimationFlags' and no accessible extension method 'AddTileAnimationFlags' accepting a first argument of type 'Tilemap' could be found (are you missing a using directive or an assembly reference?"
Try using Vector3Int as well as passing the actual flags as the second parameter(TileAnimationFlags.PauseAnimation).
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
namespace Controls
{
public class InputManager : MonoBehaviour
{
[SerializeField] private Camera sceneCamera;
[SerializeField] private LayerMask placementLayerMask;
public event Action OnClicked, OnExit;
private Vector3 lastPosition;
private PlayerInput playerInput;
private void Awake()
{
playerInput = new PlayerInput();
}
private void Update()
{
if (playerInput.Building.Placement.triggered)
OnClicked?.Invoke();
if (playerInput.Building.ExitPlacement.triggered)
OnExit?.Invoke();
}
public static bool IsPointerOverUI() => EventSystem.current.IsPointerOverGameObject();
public Vector3 GetSelectedPosition()
{
Vector3 mousePosition = Mouse.current.position.ReadValue();
mousePosition.z = sceneCamera.nearClipPlane;
Ray ray = sceneCamera.ScreenPointToRay(mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit, 100, placementLayerMask))
{
lastPosition = hit.point;
}
return lastPosition;
}
private void OnEnable()
{
playerInput.Building.Enable();
}
private void OnDisable()
{
playerInput.Building.Disable();
}
}
}```
How to make clicks work on mobile devices as well?
"""animatedTiles[0].AddTileAnimationFlags(new Vector3Int(-22, 4, 0), TileAnimationFlags.PauseAnimation);"""
Well, does that work?
Nope
It's backticks. Same key as the tilde (to the left of a 1) on a standard keyboard
And they have to be on their own line
Well
What unity version are you using?
Thanks lol
I have a different error now though
Clear the error and try again. It assumes you're using a first argument of type Tilemap.
Should mention that first...
I have both the old error and this new one:
Assets\Scripts\DiscoFloorSpeed.cs(13,75): error CS0103: The name 'TileAnimationFlags' does not exist in the current context
Ah
This was just me being dumb
Assets\Scripts\DiscoFloorSpeed.cs(13,85): error CS0117: 'TileFlags' does not contain a definition for 'PauseAnimation'
There should be a touch binding. You'll have to figure out how to implement that. I think you can get a touch COUNT, so like if there are two, count that as right click?
TileAnimationFlags is thecorrect enum
Can you show me which one? Please.
It's in UnityEngine.Tilemaps namespace.
If you still have it in the usings, it should work.
Uh, not really. I'm on my phone, sorry. If you add a binding, and go into the path and use the search. type "touch" . It should come up
Still have errors after using the namespace
Updated version (still getting the same errors as before) https://hatebin.com/nqwfzaykoj
I added this and it doesn't work.
Specifically
Assets\Scripts\DiscoFloorSpeed.cs(14,75): error CS0103: The name 'TileAnimationFlags' does not exist in the current context
And
Assets\Scripts\DiscoFloorSpeed.cs(14,26): error CS1061: 'Tilemap' does not contain a definition for 'AddTileAnimationFlags' and no accessible extension method 'AddTileAnimationFlags' accepting a first argument of type 'Tilemap' could be found (are you missing a using directive or an assembly reference?)
- Why do you have the same using twice?
Wish I could answer that without sounding like a bonehead lol
fixed now
Does it fix the errors?
Where do you see the errors? In your ide?
Unity
What do you see in the ide?
Nothing, I'm using Visual Studio
??
At least nothing jumping out saying "errors here!!!"
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Start from configuring it. After that we can move on to the errors.
Alrighty
Done, errors are now underlined in red
Just giving same errors that I get in Unity
When you hover on it, does it say "quick fix"?
Often your ide will suggest fixes
Nope
"Show potentiel fixes"
do you have using UnityEngine.Tilemaps in your using directives?
Ah, I'm thinking of vs code. Been going back and forth lately
But still, that would be it
Doesn't fix anything
ah, so the last error is due to omitting the Tilemaps. part of the type. the enum you are trying to use is Tilemaps.TileAnimationFlags
as for the first one, what version of unity are you using?
What unity version are you using?
Now it's giving me an error saying
The name 'Tilemaps' does not exist in the current context
checking unity version now
2021.1.34f1
Actually that's correct. You don't need the Tilemaps there since you have it in usings.
yeah the enum and method were added in 2022
2021 lts seems to support it too
Why are you on a beta version of several years ago lol?
I make a lot of sleep deprived decisions for quick fixes
Update to 2021.3
This was probably one of them from a previous project
I have the main camera separate from the player, so when my camera moves vertically, the sword doesnt stay in the middle of the screen
how can i make it follow the vertical movement of the camera?
public class SwordController : MonoBehaviour
{
public Transform swordCursor;
public Vector3 defaultPosition;
public Quaternion defaultRotation;
public float rotationSpeed = 10.0f;
void Start()
{
defaultPosition = transform.localPosition;
defaultRotation = transform.localRotation;
}
void Update()
{
if (Input.GetMouseButton(0))
{
if (swordCursor != null)
{
//Point towards SwordCursor Object
Quaternion targetRotation = Quaternion.LookRotation(swordCursor.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
}
else
{
// Smoothly move back to default position and rotation
transform.localPosition = Vector3.Lerp(transform.localPosition, defaultPosition, rotationSpeed * Time.deltaTime);
transform.localRotation = Quaternion.Slerp(transform.localRotation, defaultRotation, rotationSpeed * Time.deltaTime);
}
}
}
does it? the docs show 2021.3 as one of the "Versions without this page"
Aight give me a few minutes for a backup and an update
But it does say "supported".🤔
And 2022.2 NOT supported?
Anyways, if you can afford it, better to update to latest lts(2022)
That's the beta version
Naaah I aint spending money
Ahh, gotcha
I can afford it if it's free
Spend money on what?
They often start working on betas earlier than previous lts, so some of the previous version features might not be included.
What are you talking about?
making a joke on you saying "if you can afford it"
2022.3.11f1 good?
Right, I mean if you're not afraid of breaking changes.
Yes
Trying to have this project done tomorrow (almost done with mostly everything)
So how breaking are we talking
Oh well I made a backup for a reason
probably better off just updating to 2021.3 tbh, less chance of features changing
Yeah i'm installing both
Gonna use 2021.3 for this project though
please wait for me my emotional support coders 🙏
Alright, opened with 2021.3
well, opening
@slender nymph @teal viper Opened in newer version, still same errors
trying 2022 now
still same errors
wait!
only 1 error now 🎊
Assets\Scripts\DiscoFloorSpeed.cs(12,75): error CS0103: The name 'Tilemaps' does not exist in the current context
it works
thank you box and dlich, 5/5 stars, kudos
So it didn't work in 2021.3?
how do i fix this
Initialize your array.
Nvm.make sure that the index is within the bounds of the array.
items.Length is 1 index past the end of the array
Well, does your array have 10k elements in the inspector?
no#
Nvm. I'm not reading the code properly
Boxfriend is correct.
Why are you accessing something with that index?
Length is the last element index + 1 if that wasn't clear.
So it's out of bounds.
so i cant use it?
You can't use it as is. Why would you do though? What are you trying to do?
spawn things
pick a random thing in it
well that's certainly not how to get a random object from an array
Well, that's not how you pick a random thing.
GameObject element = items[Random.Range(0,items.Lenght)];
thx
how can i put the trees in the right position
they inside the ground
fix da pivot
ok thx
im geting this error
ArgumentException: Input Button Escape is not setup.
To change the input settings use: Edit -> Settings -> Input
LevelManager.Update () (at Assets/Scripts/LevelManager.cs:83)
with this code
if (Input.GetKeyDown(KeyCode.Escape))
{
Debug.Log("Sup");
}
but the problem is even with the error poping up, its still working
this not the same script or you changed it
this is the same script
then you didn't save
if (Input.GetKey(KeyCode.Escape))
{
Debug.Log("Sup");
}
If your error is not underlined in red you need to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Actually, that's a runtime exception... so no underlining
but navarone is correct
there is no issue in that code, it doesn't use GetButton, so it won't throw that exception
sorry let me explain
this is within my update fucnction and its showing no error during editor but when I start the game, its start giving this error while the game is picking up Escape key
Make sure to hit ctrl+s in the ide, then clear errors in the console, then hit play again
yeah I have it every few seconds
If the error pops up again, screenshot line 83 of the level manager script
now im getting this error
Cannot switch to actions 'Player'; input is not enabled
UnityEngine.InputSystem.PlayerInput:ActivateInput ()
LevelManager:Update () (at Assets/Scripts/LevelManager.cs:78)
are you like mixing Input systems ?
So are you using the new input? The other code was the old input manager
yes new input system
I actually tried looking how to do it with the new
couldnt find
Do you have it set to "both"?
You should probably just share the script using a paste site
📃 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.
Alright, I have what I assume is a logic issue here. I'm working on an inventory system for my game and this is the codes for the placement of the buttons. Currently I'm hardcoding the buttons to depend on each item rather than assigning an object to that button in the inventory. Everything works except for the setButtonPlacement function, it sets the button as active, but the placement of the button does not go to 0,0 as I'm trying to set it. the InventoryButtons list is a list of "Button" structs. I followed documentation I found online for changing button placement in code but for whatever reason its placing it around -700,-1000. Any ideas or info y'all need to help me?
I believe you have to actually enable the input (with playerInput.enabled = true) before you can call ActivateInput or DeactivateInput
Also, on line 83 there is no code. Is this modified from the previous error?
yes I modified it. I saw the issue there so I modified it
yeah it worked 🥹
I had to enable it
thanks
lemme know if I should put this in the general/advanced coding
Start throwing some logging in your code
And make sure the position isn't being changed locally
I have for everything else besides the last function because theres not much I can change on it besides that position that I can see in the inspector. I know the first line of code for the method is running so its not an issue of it not being called
Is it a child of an object? The inspector values are the local position relative to the parent if so
I would also say throw in a debug log with the actual position values being set
Yes the local value should be 0,0. Does the transform.position set world value?
Yes it does
There is transform.localPosition
Thats my problem then. Perfect I'll see if that works, thanks
Yessir that fixed it, thanks y'all
Hey guys, super odd question because I found a working solution to it but I have no idea why the solution works any differently at all but here goes.
The following code works:
if (triggerName != "")
{
triggerScript.addTrigger(triggerName);
}```
However this code returns an index outside of array error(wtf???):
```if (getData.frames[actionIndex].triggerName != "")
{
triggerScript.addTrigger(getData.frames[actionIndex].triggerName);
}```
I know it's really not an important question because I have found a solution but I'm trying to learn and genuinely curious/confused as to what the functional difference is between the two of these
(also I checked if the index error was occuring in the trigger script and it wasn't so idek man :/
You'd have to show the full stack trace of the error. It's not clear from the snippet shown.
Also the types of the objects involved are not clear either
get data is a scriptable object and frames is a struct contained within it
one second
That's vague though
You'd need to show those types
frames seems to be a list or array btw, not a struct
how is frames a atruct? did you create an indexer for its fields?
I'd guess they're confused and it's an array or list of a struct type
yeah this is what I meant
ah, that would make more sense . . .
It'd be better if you just showed the code
I changed it back to the old solution and now it works exactly the same so idek what happened...
I think maybe before I was adding 1 to the actionIndex variable or something and maybe I didn't save it beforehand I have no idea
I'd guess you had something else before
That being said the first example in your code snippet above is much better
It's cleaner and more efficient
i would've logged the value of actionIndex beforehand, it was probably out of range . . .
also unrelated to the actual issue, but rather than checking if the string is equal to "" you could instead use string.IsNullOrWhiteSpace
{
public ParticleSystem particle;
void Start()
{
particle = this.gameObject.GetComponent<ParticleSystem>();
particle.Emit(1);
}
void Update()
{
if (!particle.isPlaying)
{
Destroy(this.gameObject);
}
}
}```
hey everyone, i'm trying to make an impact system for my weapon. whenever a raycast hits a wall, a prefab with this script is created but i can't see the animation. any reason why this doesn't work?
Add logs or use breakpoints to figure out if that code is even running.
yeah, i got it to work
i just wanna ask is there a cheaper way of doing this?
there's a delay from when i click to when the animation plays
Are you sure it's actually a performance issue?
If it is, use the profiler to troubleshoot it.
One possible issue is if you're spawning many of this particles every frame. This would cause a lot of work for the GC. In this situations it's advices to use an object pool.
I don't think it's a performance issue
alright i'll look into that, thanks
Did you add logs to your code? Is it the code that is being late or just the particles animation?
public class UnitsCollectionController : MonoBehaviour
{
public List<AddUnitToDeckButton> collectionSlots;
private void Start()
{
PlayerDeck.Instance.OnUnitAdded.AddListener(RefreshCollection);
PlayerDeck.Instance.OnUnitRemoved.AddListener(RefreshCollection);
}
public void RefreshCollection(int index)
{
foreach(var item in collectionSlots)
{
if(item.hasBeenAdded)
{
item.unitImage.sprite = item.unitData.unitSlotSprite;
}
else
{
if(item.unitData.unitSlotOffSprite == null)
{
item.unitImage.sprite = item.unitData.unitSlotSprite;
continue;
}
item.unitImage.sprite = item.unitData.unitSlotOffSprite;
}
}
}
}
I'm getting object reference not set to an instance of an object in line if(item.unitData.unitSlotOffSprite == null). Why is that? My unitData is referenced
Ok figured it out nvm
Hey, does someone know how can I create a good icon for my app created in unity for Android?
Cause in my phone, the icon that I've chosen it's blur
And it is not a resolution problem because I have exported it from Photoshop at a very high resolution
Ive ran into a weird problem with a wage equation that wont return anything but 0.
float payfloat = (((worker.Wage*worker.Level) / 480)*50);
Worker.wage is an int at 100
Worker.level is an int at 1
I ran a debug for those values and that works correctly. But the payfloat never returns anything but 0 all the time.
Anyone have any idea what im doing wrong?
It should return ~10 in my books :/
You are doing integer division.
float payfloat = (((worker.Wageworker.Level) / 480f) / 50f);
I just did that and it works now. What in the world? , i thought if i didnt type "f" it was counted as that in this case
No, you are performing integer division, and assigning the result to a float
float result = exampleInteger / (float) anotherExampleInteger; is how to do it when you have two integer variables
Ahh. But i dont need a (float) infront of my wage*level part of the equation?
As long as one of the arguments is a float, it will perform floating point division
I am having problem here as even after adding prefab to the gameobject in the inspector it is showing missing variable
Ahh gotcha. Thanks alot , good to know for later equations. Save me some headaches 🙂
Search the scene for that component and check what every one has it assigned
i have checked it
You have no code in the start function that searches / resets the prefab?
no
Can you show the hierarchy when you have searched t:Player_rotation
Do both of those objects have the Bullet Prefab assigned?
no
Then that's your issue.
thanks
in the above code my bullet object is just remaining static after shooting and is not moving forwarrd what should i do
You need something to push the bullet forward. Like a script on the bullet prefab
donethanks
what is a good place to start building a chat interface similar to how you text on a phone? any components I should consider?
my plan is to make a prefab for a message, and then programatically add these to the window. I'm not sure how I'm going to handle eventual scrolling though?
I'm also unsure how I'll handle that some messages are longer than others, so they ll differ in height
not code question
you may get started with scroll rect, content size filter, vertical layout group
hey so how do i set like a new key mapping thing
trying to make my player be able to sprint
could you be more specific, I have no clue what you are trying to accomplish.
so in my player controller i want to add sprinting
this is the code i have rn for the sprint part
if (Input.GetButtonDown("Shift"))
{
playerSpeed = playerSpeed * 2;
}
will that work for if the shift key is pressed
That would increase the speed everytime you press the button
You need to have a Basespeed variable and a current speed variable.
So when you are pressing shift - the currentspeed would be Basespeed *2 , and when not - currentspeed is basespeed
if (Input.GetButtonDown("LeftShift"))
{
playerSpeed = playerSpeed * 2;
}
if (Input.GetButtonUp("LeftShift"))
{
playerSpeed = playerSpeed / 2;
}
i have that aswell
oh wait no that wouldnt work
if (Input.GetButtonDown("LeftShift"))
{
playerSpeed = playerSpeed * 2;
}
if (Input.GetButtonUp("LeftShift"))
{
playerSpeed = playerBaseSpeed;
}
smth like this
Id put it in the shift aswell
So playerspeed = playerbasespeed *2
Just incase something interupts the "Getbuttonup" function later on in your development
alright
Like a menu , or something like that
but the part that gets if the button is down or not is good
Yeah thats good.
Ohh , have you not added the shift key to the input?
Ohh this input system is new. I havent used it im affraid. I useually put in the keycodes instead of the input system.
So either you look up a tutorial for how to enter new inputs into that system or use : if (Input.GetKeyDown(KeyCode.LeftShift))
Or you can try and just get a value of that key (0-1) and use that
so how would i have it so it plays a certain animation while its active
within update,
if(keyvalue == 1 && animationNotYetStarted) {//keydown
doAnimation();
animationNotYetStarted = false;
}
the bool is so that it doesnt continually start over and over
doesnt it only do that animation once though
Hi, I've noticed my code isn't as colorful as when I check out tutorials, what makes my code show in different colors ?
you might not have intellisense on
I!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
If the key is pressed it will do it once. Within your animation function you can set it up so that it changes that bool value when it finishes running the animation so that it automatically does the animation again if the key is pressed.
ok thanks
now time to figure out how to make a push and pull mechanic where you can push objects and players away and pull objects and players to you
that will be fun lol
Wasnt there like a possibility to set up a default scene that you are loading in when editing a prefab? im trying to find it but I cant
Like editing a canvas prefab with a pre-set scene to emulate my other UI
hey i have made a small target prcticing game and have done everything but noow its not working properly its when colliding its not getting destroyed and giving points so was asking if someone can somehow help
Can't help without seeing the code
Hello guys, do you know how i can enter in each element of this?
Drag/Drop or Select, Type, Click
Is that an element you have made yourself ?
If it is , then you need to add a function to apply the values
items[i].Id for example. Where i is the position of the element in the collection
it seems like a struct they made
in a for or foreach?
i dont understand sorry. That's how I'm trying
You can't use foreach here
Well, you can't use a numerical index if you want to use foreach
Just use the item variable
index outside of the loop , but for is better in this case
item.Id
Well what do you actually want to do?
Access a single element of your list, to get or set a value, or go through all the elements of the list
I have an item and I want only by assigning the id to put all the other values such as description, etc.
So you need to find an element that has a specific value in its Id variable
You can either use for, or foreach for those
Ahh i see
Yes, but I have lists within a list
I need acces for example to element 0 and id of element 0
There's no lists in lists here
How is this a list within a list. This just looks like a list
Theres a few ways you could do this.
I would use a master list with all the IDs and properties already filled in.
Then you run a foreach item (Inventory) Against a foreach Item(Masterlist)
And if they match - set the values to be the same as the master list item.
Or you could use a foreach loop on the items there and use a switch case on the ID's but thats not recommended.
You do items[0].Id to access the ID of the first element in the list
yes but i need comprovate all element
sorry i dont understand too of programation
Erjoni, you want to go through all the Id values of your elements right ?
yes
of this
yup, SPR2 has given you the answer
For loop, foreach loop can both do that
so for my player controller script i have it set the playerbasespeed to 5.0f but in unity its set to 2 for some reason
public float playerSpeed = 5.0f;
public float playerBaseSpeed = 5.0f;
editor will override the value in your script
^
how do i fix that then
Im going to try
i guess i canjust edit it in the editor
you need to only replace the 0 in his code here by a variable that a for loop will go through until a specific number you set. For example here the end of your list
Edit editor , put value as private or put the value in the start function
make them private, or just edit them in your editor if you have multiple instances and them will have different speed
What is the learning curve to advanced enemy AI in unity?
just keep stacking them logic gates
hey what code do i use additionally to disable a component of a instantiated object
component.enabled = false;
so its like Instantiate(gameobject).component.enabled = false ?
no
where do i put what component i want to disable?
you have to get the component first, then you can enable it . . .
GameObject go = Instantiate(gameobject);
MyComponent component = go.GetComponent<MyComponent>();
component.enabled = false;
thanks tho still trying to understand it
thats what the docs are for
Also guys ive never tackled multiplayer before
Just for a basic overview, is it hell to set up AND test
yes unless you really know what you are doing
good luck, my friend . . . 🫡
the road ahead is perliess and fraught with danger . . .
It’s dangerous to go alone. Here take this https://docs-multiplayer.unity3d.com/netcode/current/tutorials/helloworld/
Tutorial that explains creating a project, installing the Netcode for GameObjects package, and creating the basic components for your first networked game.
Hi, i have made a Programm with whom i can open various Video- and Audioclips and since i need to store these custom made Clips somewhere and need to load them into the Program when i click a Button, i use the Resources Folder at the Moment. Of course, since these are quite a few Clips, i need to order them in a Folderhirarchy. Now i have the Problem, that the Program works in the Editor, but not when builded, i think because Unity turns the whole Resourcefolder into one File, so that the Code adressing the Folderstructure does not work anymore. Now, eventhough i could question now, why Unity even makes such a Code, that does not work when builded, in the first Place, but i just want to solve the Issue and load my Files at the Moment. Is there an
Option 1: A Command to load Files from the Resource Folder with respecting the File Hirarchy / Data Path, or
Option 2: Store Files in another Folder with another Load() Method, so that this Folder does not get turned into a File by Unity when building?
Example of useless Code:
Videoclip = Resources.Load<VideoClip>("Subfolder/Videofile");
// Works in Editor, but not in Build
It was kinda blocking my Post, wich is far more interesting ;)
I don't see any reason why that wouldn't work in a build. Can you show the thing you're loading from resources in the project window? With the full folder path in the project visible?
I have set up visual studio and everything works fine when i open VS directly from the desktop but when i open a C# script within unity the autocomplete and stuff doestn work? i am so confused?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
yes i have done that 2 times but it doestn work as intended
hey so i have an enum in a static class like this:
public static class Loader
{
public enum Scene
{
MainMenu,
SceneLoader,
Lobby,
CharacterCustomization,
DemoScene
}```
and i have accessed its ToString method before like this:
```cs
public static void NetworkLoad(Scene target)
{
NetworkManager.Singleton.SceneManager.LoadScene(target.ToString(), LoadSceneMode.Single);
}```
which gives the name of the scene, like Scene.MainMenu.ToString = "MainMenu".
i'm trying to use that in another script though and getting compile errors:
```cs
switch (sceneName)
{
case Loader.Scene.CharacterCustomization.ToString():```
this gives me the error `The type name 'CharacterCustomization' does not exist in the type 'Loader.Scene'` which is weird because it does and also if I remove the ToString it resolves it perfectly but gives the error `Cannot implicitly type Loader.Scene to String` as expected.
what am I doing wrong?
To start with your first code example does not access your enum.
Secondly you use ToString on an instance of a variable not of the type itself
Loader.Scene.CharacterCustomization is a type, it doesn't have any sort of ToString function.
You could store it in a variable and ToString that variable
and I think there might be a helper method in Enum that gets the string of a specified value
I feel stupid, this is like the 15th time im setting up ui stuff and now it doesnt work like it did the other 14 😄
I have
- Event System
- Graphics Raycaster on the main Canvas
- Event Setup for the Button
Clicking it does nothing though, I installed the new InputSystem for the first time tho, any ideas what might be missing?
(Using the last overload on the page since you have the enum value and don't need to cast it from int)
Did you click the button on your event system to convert it to the new input system after installing it
Switch cases must be constant values so the approach won't work either way
Yes
this right?
So, at the bottom of the inspector for your event system, you should see info while playing about what's currently hovered and selected and whatnot. Play the game, hover over your object that's not responding to clicks and see what your event system thinks is going on
You might have an invisible collider/raycast target in front of it
so am i better off just using string constants here for comparison?
I dont see anything like that
if sceneName is a string you have no other options if you want to use a switch
This box here. Are you in play mode?
Yes, but it only shows what I have selected in the hierarchy
Oh i should mention i am on the 1.8.0-pre version for the search field fix
So if this is in play mode and you're hovering over the button it's not detecting anything. Either your button isn't a raycast target or your canvas isin't using a raycaster at all
Can you show the inspector of the button and your canvas
And the canvas?
Those are the 3 parents
Also you seem to have a runtime and editor script with the same name, causing that error you see. I'm not sure if it's related but if that script is what you're expecting to happen on the button that could be
No I have that error figured out, its from the entitas library im about to fix that next
Can you get any UI elements to respond to the cursor, or is it just this one specific one that's not working?
Added one like this: https://img.sidia.net/ZEyI5/KaCUyONU44.png/raw
and it reacts to hover & click
weird oO
well as soon as I put it into UIMainMenuScreen the reaction stops
oops, figured it out
Oh didnt know each one needs one, good to know, thanks for the help 😄
welcome to floats
I didn't think it did either, but I guess that's good to know for me as well
floating point be like
Now i made a Video to remake the Error in a Test Project and ... the Error did not occur. The Command works also in the Build. Now i feel like an Idiot, and yea, ill upload the Video anyway^^, and i think i must have done a mistake somewhere else
guess it knew you were watching this time ¯_(ツ)_/¯
Yeah, but why would the complete value of the vector3 be different than the individual y component? I'm guessing it does some rounding?
oh, maybe it has some ToString function that rounds yeah
I think it might be because of
Directory.GetFiles
that cannot find the File anymore.
is there a
Resources.GetFile
? for the File Name?
If you put a file in a "Resource" folder
The ToString function for Vectors rounds values to two decimal places
you can just get it by Resources.Load<Type>("Name");
oh nvm, missread what you are trying to do 😄
maybe Resources.Load<>(Filename).GetFileName()?
So, once it's in the build it ceases being a file and become an asset in the build. The Resources folder just tells unity to include that file as an asset, even if it's not directly referenced anywhere. The filename (including paths) is still how you index it, but you can't do a normal directory traversal of it because it's no longer a real directory
how do i get the filename?
Since you need the file name to reference it, why not just use that?
?
well, i would like to do, but what is the Command?
i am using
Directory.GetFiles
atm, but that does not work anymore after build i think. so is there an
Resources.GetFiles
Command?
I'm not sure what you mean. If you just want to get all the files in a directory, there's LoadAll:
https://docs.unity3d.com/ScriptReference/Resources.LoadAll.html
!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.
for example i use atm
Amount_Var = Directory.GetFiles(Application.dataPath + "/Resources/Subfolder/" + Int_Var.ToString()).Length;
how do i do this, if i have to use the Resources Command?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
in this both the objects are not colliding and are bypassing each other and are not destroying
this will only work in the editor
it's directly poking around in your project folder
None of these files will exist on disk in the built game. Everything will be stored in a few big asset bundles.
Resources.Load and Resources.LoadAll will be able to retrieve assets that are stored in a Resources folder.
These do not load "files". They load assets.
If you absolutely must think in terms of files (e.g. you want users to be able to add their own files or editing existing ones), you want StreamingAssets.
If you just want to know how many assets are found at a certain path, then call LoadAll and then check the length of the array
Yea, ive found that ina Forum, now i must build an Array with an unspecific Size^^ - yay - i hope he does bother if i use a List instead
How do i:
Array = Resources.LoadAll<Folder>(Subfolder);
Length = Array.Length?
count Folders in the Resource Folder with a Command? Without counting Subfolders wich are further down below in the Hirarchy?
the folder hierarchy doesn't exist when the game is built
i am not aware of a Folder type
there's UnityEngine.WSA.Folder, which is some really specific thing for the Microsoft Store
What are you trying to accomplish here?
https://hastebin.com/share/opaxemijov.csharp
in this both the objects are not colliding and are bypassing each other and are not destroying
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
The Three Commandments of OnTriggerEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 3D Rigidbody on at least one of them
done
Show the inspectors of both objects
I try to direct through Code through the Subfolders. Depending on what the User does, a different Sound has to be played
I guess i have to use a different approach and make a "case" scenario in the code, instead of doing it in the Hirarchy, sad, takes more work, but ok
Presumably this is going on the gun object? If so, that trigger isn't follwing the bullet collider but rather the gun collider
no for this i created an empty object for spwaning
ur moving with translation probably wont give accurate result either
still the same way. The OnTrigger needs to be on one of the colliding objects.
but if i do this than i cannot check the number of targets
When handling online multiplayer do I need to set up my player controller in a different way? Just curious how it would work..
I just want to make sure I am building my game in such a way that it isn't extra rediculous to add multiplayer support into it. Any advice ? Any videos or recommendations on this? I don't want to build my system in such a way that I can't easily expand upon it and add the multiplayer in the future
For example, I have a sword in my game that is non-triggered and an enemy that is. I have the code on my enemy to detect on trigger and checks if the object is a sword. Gets the script on the sword (or bullet in your case) to check how much damage it did, and removes the amount of health from my enemy
You can still reference your spawner script in your bullet script
how
Multiplayer is difficult, even more difficult is not designing a game for it in the very beginning.
Adapting multiplayer to singleplayer that is already established is way more diffcult
Which one has the Counter script on it
counter scripts is on spawn manger gameobject
Which of these two objects is the spawn manager
none
So why did you show me these two objects
both are different gameobjects
2 ways. If its a parent object (GameObject.parent) or GameObject.Find("Spawner").GetComponent<Counter>().count(); or ending with whatever public variable/method
I asked for the ones involved in the collision
So the Counter object and the thing you're expecting it to collide with
^
theses both are involved in collision but this script is attached to spwanmanage gameobject
Thats why I said your collision script must me on a colliding object
your spawner does not collide
no
These two objects might be involved in a collision but you want to know why the code in Counter isn't running, so show me the objects involved in the Counter object's collision
prefabs attached to it collides
Its not attached, it only references it
Can i do this with StreamingAssets?
Like:
StreamingAssets.GetFiles().Length;
?
Do you have any resources, I am only 3 weeks into my project. Just getting some basic systems working.
I feel like I am not too far into it to where this will be a problem currently. I just wanted to make sure I prepare and build for it now, before it is a bigger issue
You've cropped the SpawnManager inspector, where is the collider
You're giving us parts of the inspector, we can't tell what is what.
#💻┃code-beginner message
Commandment 1
ok
Depends many things, one being the framework you use.
if this is your beginner project , I would not recommend be multiplayer though. Learn on the many frameworks that exists and why one is better than another etc.
Both objects involved in the collision have to have a collider
they both have sphere collider
Okay, so show that, don't crop it out
Show the collider on SpawnManager
It is head to head multiplayer. Not a ton of players. Local and online. It needs to be done this way.
To help clear it up, there are 3 object. Bullet, enemy, spawner. Spawner has the counter script and no collider. Correct?
Easier if its slow paced multiplayer like Amongus or even turn based.
Start with netcode.
yes
Why do you keep showing me unrelated objects
SpawnManager has the script
yes
You are checking for a collision with it and something else
so show me the collider settings on the SpawnManager
@polar acorn this may clear it up for you
no it is spawning the things that are colliding
||I know that but I'm trying to get them to realize that||
Irrelevant. The OnTriggerEnter code is on SpawnManager
okk
So you're checking for when that object collides with something
Does SpawnManager collide with anything
yes
Hey sorry to bother i know youre in a conversation but does someone know how i can send data like variables from unity into python?
i tried it wiith chatgpt but somehow my gamw wont start if i use that so pleas help ;-;
So yes, it does collide with something?
Show the collider for it then
What do you mean "send data into python"
Using this game as my placeholder graphics.
Okay, so does the object that SpawnManager collides with have the tag Target?
i want to make a vr aplication for something and i am trying to send the rotation from my player to a script so that i can use the rotation there, please dont ask why, its complicated xd
yes
(python script in vs code)
Show the inspector of the object tagged Target
So I am using dir.GetFiles("."); to get saved world data in a /Saves folder. Now I want to make it so world file is not saved into main /Saves folder but into a custom folder created in /Saves folder. Custom folder is created but how do I go into that folder and get my world data file?
No, the object tagged Target
The why is because thats very tough compared to just using python scripts in Unity. If you're using puthon because you don't know C# well @undone stream, you'll need to know C# anyway
*compared to just using C#
See that the tag says "Untagged" and only the NAME is Target
As in, like, you want to write a python script file with some data from unity? Or is there some sort of running program using the python script that you need to feed data from Unity into?
ok
Explain what you want to actually accomplish.
not "sending data into python"
So, you want all the saves in this folder, and any saves inside of folders inside that folder, right?
I got a Vr headset and im trying to make a 3rd party software so that i can play A "normal game" (not vr game), inside my VR headset,
im trying to accomplish that by sending the rotation of my player (headset in UNity) to a script on my PC that is then turning my mouse accordenly
Okay, so, when an instance of this prefab makes contact with your SpawnManager, it should run that function
You can probably get away with most of it by using Netcode components like NetworkTrasnform and NetworkAnimator
ok
i guess a simple-ish way would be to use websockets
Yeah, so I have a /Saves folder and inside this folder I have a folder with name of this specific world name, and inside this folder is the world data file
i later want to "release" it so friends can also use this, does this still then work when done and builded?
I will probably have to hire someone in the future to really do some of the stuff I need. I want it to be playstation, xbox, and pc crossplay..
Is it as difficult as I think it will be
Can you not use an existing software to stream your PC to your VR like SteamVR? Or is it a Unity Desktop game you're wanting to specifically use
sure. you would be having the python script start a websocket server, and have your Unity-based program connect to that server and send rotation data
I dunno how the latency would work out
Saving works fine but I am struggling with loading world data now after changing file directory
Unity documentation says “Rigidbody2d.MovePosition is intended for use with kinematic rigidbodies.” But… what if I want to move a dynamic RB?
you are already using DirectoryInfo why dont you look at the Directory class?
Because every save has different save folder name
i want to use unity cause unity already can read the information of the headset perfect, it then can turns action like "pressing "y"" on my controller into some type of data and send it to another script
So, what you'd want to do is use Recursion. Make a function that takes in a directory and returns a list of FileInfo. Then, you can use EnumerateFiles to get all the files in this directory and add them to your return list. Then, you use EnumerateDirectories to get all the sub directories, and call this function again on those directories, adding the returned files to you list
Then you should probably be using velocity and/or add force
its possible but just very difficult. if you're serious about your project then sure, it would be smart to hire a network expert to go in with the final polish
im just using unity cause i dont want to make a new software from scratch whcih then reads the rotation and position of my headset cause that probally way to hard
In my case, I have my rigidbody moving in the reference frame of another object. So I first want to translate it (to sync it to the reference frame), and then apply forces. But using transform.translate seems janky af
I agree. This is not my expertise so I can't help much here.
Ok I will try that
Yeah, I am. I just want to get it set up properly, before I build too much and have to go backwards or start over
i dont know if you meant me but anyways thanks
I did
i hope what I am going for makes sense
My player is moved around primarily by forces. But if he is on a moving block, I want the block to transfer any of its motion to my player (but I can’t use friction).
@navarone is netcode for gameobjects good to use? for a 1 vs 1 online situation?
So, if your intention is to actually teleport the object, you'd want to set Rigidbody.position. MovePosition is for when you want to set a destination and respect all the physics behind it like collisions and whatnot which can very quickly cause some major jank with a dynamic rigidbody. If you want your dynamic rigidbody to just go to a place, you can set the position of it similar to how you can to a transform, and while it won't calculate physics along the way, it'll still actually move the rigidbody to the target location right away instead of lagging behind by one timestep
that is what I have been doing, but I am getting collision jank, because I can be translating my RB’s collider into another collider
idk i wish there were like a joint2D that would just transfer it like a force
but all the joint2D I try also block the rigidbody’s own AddForce commands to move it
Yes you can find some pretty good tutorials online
I personally enjoyed using the built in components to make easy prototyping. You should try it out first
Alright thank you. From where I am at now.. I have player movement, a play selection system, and receivers run the routes based on the play selected using some waypoints. Lots of just other basic scene setup. I don't think I am too far in to start planning for it
Yeah definitely start the netcode now because there a few implementations you’ll need
I am not sure if i am supposed to ask this in this channel, but basically I have a game where I have a sprite (square) and I have tried to import a .png of a square but now the square is way bigger, how do i make it so that the png i am trying to import is exactly 1*1 units big?
this is not a code question no
Ok, just happy I asked about this today.. I just had a feeling.. I should be planning for this now.
also fix your PPU size @celest ravine
where do you ask it then? it's not shaders, nor vfx nor procesing... ?
#💻┃unity-talk at very least
Pixel Per Unit?
right
yes
ok sure
Make sure you keep your objects at the same ppu and plan around that size
Does acceleration in unity just work like velocityNext = velocityOld + acceleration * Time.deltaTime?
that would be valid, yes
acceleration is a change in velocity over time
like how velocity is a change in position over time
i have to ask because classical physics only apply if you make it apply
I’m thinking about making a kind of different rigidbody API
let me know if this sounds dumb;
- Make singleton class with a list of all rigidbodies in scene that I need for calculations. This singleton class keeps a record of current position, previous position, defacto current velocity, desired MovePosition, and totalForce.
- Give rigidbodys extension methods that are used instead of MovePosition or AddForce, that only go tell that singleton to update values.
Script execution order:
- Singleton log: go through all rigidbodies and create new logs (velocity = old position - new position….), totalForce = 0….
- All my scripts do their thing, adding forces etc to singleton
- Right before physics calculation, singleton class (or some other helper class) goes in, and combines all the MovePositions etc to a covesive final result.
Good/bad? Pointless? Ideas?
So let’s say I have a player on a dynamic block that is on a kinematic platform moved by a kinematic motor moved by MovePosition.
ah, you need to manage frames of reference
exactly
so if multiple items down the line call MovePosition, it doesn’t work
because MovePosition commands overwrite each other, and only get executed in physics step
transform parenting doesn’t work… because idfk why
because parenting something means its transform is getting messed with by something other than the physics system
apparently having a dynamic rigidbody on a kinematic moving platform was not a common situation during unity development
i understand why, but unity devs should have made a way to make reference frames work easily
so you want separate lists of GameObjects separated by movement type and you run their movement in order to avoid being overriden?
even a joint. I would take a Joint tbh that moves an item, while letting it move freely
correct
so if the platform moves +2x, and the block moves with a force for +1x velocity, it can just get transferred to the player on the block on the platform
idk why this is so hard to do
@rich adder so if I build a game that does local multiplayer.. would I need to do a complete overhaul of the code in order to make it online multiplayer. Because all of this netcode stuff is something I will need to learn to use, but I was just wondering if for testing purposes to get the base game working it would be ok local? Or is that going to be just way too much work to convert into online also in the future??
or anyone that has input on my question
that's similar to an update dispatcher i use to put MonoBehaviours in a separate list for FixedUpdate, Update, and LatUpdate and run those in their respective methods . . .
i’m just sad that this feels so basic, yet so difficult
im making online game with fishnet rn for the first time and ive used most of its features by now and it was a lie when mfs kept answering me same question with "complete overhaul of the game"
stuff happens similarly just code moved around
LAN or Online will be the same
I was gonna make couch co-op for testing. I feel like the code I use for that would translate fairly well into lan and online.. it is just hurting my brain a bit. Trying to understand my next step you know
Was it built for local multiplayer at first? and then you adapted it? How difficult was it to do?
I guess I am just at a little roadblock, because I have never done the lan or online, and was thinking I could build it local and down the road turn that to online multiplayer
yeah, i think figuring out what GameObjects are attached to the moving GameObject in order to add that moving GameObject's velocity/force to them is the hard part. you may need some type of node or connection to each object to pass their velocity data . . .
yea at first could only connect in the same network but switching to proper multiplayer was open port in my router and set ip address in my network manager lmao
You should really use something like Relay
So you have a server the clients connect to instead of flooding their routers with excessive traffic
I did the hard part of making a tree.
It’s basically a hierarchy, but for reference frames that aren’t actually parented to each other
my game is not gonna be self hosted but one single server all clients connect to, its fundamentally limited game to about 100 players maximum on single server/map so ye
what I’m struggling on is the final piece: The line of code that actually makes them move
Oh I meant I was designing my game to be playable couch multiplayer not lan.. because I have never worked with that stuff.
I was wondering how hard it would be to convert true local multiplayer to lan and online
What hosting service are you using?
Oh local you mean same screen ?
Yeah, I was going to build it that way at first for testing..
Im not that far yet but I was looking around gonna try playflow probably
So i'd be screwed if I did it that way?
No but you'll notice sending info between clients is very different than working on the same session
idek where to ask about this but my camera just isnt doing anything
am i being really stupid?
It's just frustrating to have my progress come to an abrupt stop.. cuz I am feeling the flow, but if I have to learn this stuff now, it's gonna be a big slowdown
It just feels like I don’t have tools that work to sync their movement.
-MovePosition requests overwrite each other.
-Moving transforms makes janky collision
-I can’t just add force to a target position
-Joint2D either don’t sync motion OR block the child itself from moving with its own scripts
-Parenting transforms just doesn’t work
-Physics scenes don’t seem scaleable for this
I’m just so frustrated
Peer2Peer?
No same playstation. 2 controllers type of thing
Ohhhhh
But I want that and in the future to add in LAN and online
Then you can use local device IP
I was just hoping I could translate it down the road
could start now looking into what you have to port over
but I was worried I would run into major issues if I didn't plan for it now.
Figured multiplayer is multiplayer, but I am naive
make a separate project and play around with just network package
you won't know for sure until you dive into it
Whatever the player 2 controller does seperate it from the player 1 controller
and then have the game manager and stuff be shared
so if 4 people playe your game, your scene is running 4 times. at different rates, so sync info between that is the challange
Sorry, i'm not a complete moron.. despite how I sound right now lol... I am just overwhelmed with the revelation that I can't really progress until I understand something I wasn't planning on learning until a ways down the road you know?
Feeling like a deer in headlights right now lol..
Multiplayer is all about maintaining consistency. You can no longer rely on everything happening in a specific order.
It's a lot to think about.
Im not saying you are, its something you have to try out before you know what you need to port over from your current project
Is there a way to upload an image in playmode using a button? (Like the "+" button on discord. To upload an attachment)
Yeah, using indexes for a lot of stuff, and set up my script load orders
what genre will be ur game btw?
idk, but maybe you should be using a command pattern?
no built in way no..sadly..
like, before any scripts execute, go get every player’s controller inputs for the frame, then use them.
this probably sounds naive, but that is my first thought
it might be easier to do on mobile though
That's what I'm aiming for.
idk, maybe InputSystem already does that?
so you want to pick a file from your computer in the game?
From your phone. When you click a button, it must ask to open gallery and stuff.
I feel like it is going to be a ton of trial in error. Right now I am racking my brain on a physics equation. It's the only one I will need for my game.
But when the qb passes the ball (has a pass speed) and the receiver is running a route along the x and y axis. at a speed.. I need to calculate where a straight line would need to be drawn to make the ball and the receiver hit each other in stride.
its distance + velocity (time) something along those lines
Haven't tried but you can look into
https://github.com/yasirkula/UnityNativeGallery
It's used to for example change a pfp ingame or adding an image in a chat. I was wondering if it's possible, cause it's very hard to search on google
this is a common problem: shooting a projectile so that it'll hit an object moving at a constant speed
I need to figure that one out
it's important for things like shooting at a player in a vaguely threatening manner
you need some math help for your pass?
oh dear god I googled "leading target math" and got this site
this is amazing
there's your answer. job's done!
hmm. Thnx, I'll take a look

Like if player and the projectile were both moving along a single axis.. it is easy.. but if my receiver is going left 5 units, then down 3, then left 5... how in the world do I figure out where they will be
Now that I look at it, it is so obvious! How did I not think of that?
Same.. I really didn't think to call it leading a target.. which is literally what it is
i'm struggling to find a good resource for this, somehow
Here, I show you how to make AI of different complexity for shooting at a player. All the way from 6 nodon AI to 150 nodon AI, I've got you covered, fam.
Level featured in the video: G-002-DXP-XXF
Sample code for AI turrets: G-003-P0N-667
0:00 Intro
1:10 Basic AI
4:35 Medium level AI
8:57 Jump hard
10:00 Let's go even further beyond
10:55 Comb...
I did something like that in game builder garage, which has extremely shitty ability to do math/equations
i do have some useful approximations also in that vid
I have the main camera separate from the player, so when my camera moves vertically, the sword doesnt stay in the middle of the screen
how can i make it follow the vertical movement of the camera?
public class SwordController : MonoBehaviour
{
public Transform swordCursor;
public Vector3 defaultPosition;
public Quaternion defaultRotation;
public float rotationSpeed = 10.0f;
void Start()
{
defaultPosition = transform.localPosition;
defaultRotation = transform.localRotation;
}
void Update()
{
if (Input.GetMouseButton(0))
{
if (swordCursor != null)
{
//Point towards SwordCursor Object
Quaternion targetRotation = Quaternion.LookRotation(swordCursor.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
}
else
{
// Smoothly move back to default position and rotation
transform.localPosition = Vector3.Lerp(transform.localPosition, defaultPosition, rotationSpeed * Time.deltaTime);
transform.localRotation = Quaternion.Slerp(transform.localRotation, defaultRotation, rotationSpeed * Time.deltaTime);
}
}
}
DUDDDE this is exactttly what I need
you're basically solving a system of two equations
your choice of angle determines how quickly ∆x and ∆y change, and you want both to wind up being zero at the same time
@buoyant knot OH shitt it's your video too. Thank you. I always was awful at math.
the annoying part is that those values are both going to depend on t
First person or what?
the youtube vid I sent has the answer, I’m pretty sure
Oop sry forgot to mention that
ya first person
So you look up and the sword stays in place instead of following the camera?
it follows when I turn my head left and right, but not up and down
I don't know. I am gonna watch the rest of your video @buoyant knot because that projectile is leading the character
Thank you for sharing that
Put the sword in an empty parent container and rotate that parent on the X axis with the camera
sure
there are a few approximated versions as well, which aren’t perfect, but a lot better
How hard was that for you? Or are you a math fiend
Stormtrooper AI lol
Hello guyz , i have some logic problem with TimeTickSystem. I want a code that exxecute three time in a row , so i'm a doing a for loop to make it go , but he litteraly just sprint in the for loop while counting only to twenty. Any advise ?
Ooh tysm!
would i like reference the main camera and then get its x rotation or smth?
You can just rotate that parent in the same script as where you rotate the camera
Or whatever you like
Do you have more context?
yeah , i want something that instantiate an object x 20sec
ohh okay thank you! Will do!
so i'm doing a loop for executing the void that instantiate with parameters of timer
every 20 seconds?
every 20 ticks*
Have you used Coroutines?
nop
Some info missing here, not sure whats going on
sorry xD i'm using a tick counting , each tick add 1 to a variable , and at 20 , it make start a fonction
but i dont understand why does it skip each loop , then start counting
how is it possible for a code to run only after the end of the loop ?
You showed like 2 lines of code so Im still not sure whats up
!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.
The loop runs first, then the code after it, thats how it goes
You should reset buildTick to 0 when 20 is reached, right?
oh maybe
OR, check it like if(buildTick % 20 == 0)
feeling stupid if this is the answer
Gonna have to watch the video a couple of times. That is wild. So to make a perfect calculation it is rough it appears
that is the exact calculation. I could not do it in game builder garage because that engine is suck at math. But this would not be hard for you to do in unity, assuming I didn’t fuck it up
nop not working too
note; Time of flight can give a nonsensical result if the pass speed is slower than the receiver’s run speed
What did you change? Put your code in a paste site
and I’m pretty sure the +/- is going to have only one of those two numbers being positive. so you’d ignore the negative time
Things don't hurt my brain often.. but skipping trig class and messing around in high school didn't pay off in the math sense
I appreciate your help very much
Wondering how i can set my player to rotate with my mouse yet move the same way as i coded it
That will never happen luckily, but I wonder why that is
I dont know how you coded it.
Oh and also, I'm gonna have to flip the calculation a bit on the x axis when the player is traveling the other direction it seems
Can i show it or nah
You should show it if you want help ofc
Also what kinda game? 2D topdown, platformer?
because if the receiver runs away faster than the ball can chase him, they will never touch
the solution is complex (imaginary) time, which makes no sense
3D topdown. First is my third person camera. Second is my Player Movement. I have other physics code with my movement but i dont think that is required here
i would honestly evaluate the + and - versions of that equation. Assert that exactly one is positive. Then use the positive one, and continue with that time.
Implement a basic mouse look, then rotate the move direction with that mouse rotation's Y angle only
How far in your education did you go with mathematics?
I have a PhD in chemistry, but this is just highschool math
not a smart move lol
Something like moveDirection = Quaternion.Euler(0, lookAngleY, 0) * moveDirection @queen adder
Or just rotate orientation I guess
Would i put this in Camera or Movement Script
Probably movement since it doesnt affect camera really
I bet there are tons of tutorials that solve this though
Its basic 3rd person controls
Does the equation you send me account for the fact that different players can have different throwing velocities. I don't want the throw velocity to be based upon any factor other than what it is set at for the player's stat. If that makes sense. I am looking over the equation you sent and seeing what variables I have and what I need to create
it is a function of whatever throw velocity you plug in
is it better to use rb.velocity or rb.addForce for horizontal movement when creating a platformer?
I would make a function: CalculateThrowVelVector(Vector3 receiverPosition, Vector3 throwerPosition, Vector3 receiverVelocity, float throwSpeed)
Ok, thank you. I was looking at the final line you wrote
Was just trying to understand what that was for. Since the throw speed was already defined.
Some of the other variables like angle, and (vector between thrower and receiver), and distance etc can be calculated from just those variables
you have throw speed. you need throw velocity, which has direction
Ok, I wasn't sure, because I am not using actual physics in my game. This is just for the animation of the ball sprite to travel
ie you know how fast the ball moves, but not where to throw it
The ball won't be bouncing or dealin with gravity it is all done through animation
yeah, this assumes none of that
this would be substantially more complex if you add gravity or anything to the mix
Speed + direction is velocity. I forgot that speed and velocity weren't interchangable
yeah. if you have that function, you can use it for any such case. plug in different throw speeds etc
that way you only code once
Makes a lot more sense now. Thank you very much for your help.
sure. also I think I used Vq and Vp interchangably for speed of QB and pass. They should both be speed of pass
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pipes : MonoBehaviour
{
void Update()
{
if (PipesController.Instance.canSpawnPipes == true)
{
transform.Translate(Vector3.left * Time.deltaTime * PipesController.Instance.speed);
// Destruye el objeto si toca el lado izquierdo de la pantalla
if (transform.position.x <= -Screen.width / 2)
{
Invoke("OnPipeTouchedLeftSide", 0);
}
}
}
private void OnPipeTouchedLeftSide()
{
Debug.Log("holaholaholaholaholaholaholahola");
}
}
``` Does someone know why the debug low is not working? It is suppose to be printed when the object that contains the script collides with left side of the screan
Maybe the player isn't actually triggering that collider
Or else you would be getting that debug log
I believe the Screen.width is in pixels, not in world coordinates
wich collider
I think you would need to use the cam.ScreenToWorldPoint function on your camera.
how would be that?
1 sec
sure
You would need to add something like this @dry tendon
[SerializeField]
private Camera cam;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Debug.Log(cam.ScreenToWorldPoint(new Vector3(Screen.width, 0)));
}
Well not the Debug.Log ofcourse you would replace your Screen.width, with the cam.ScreenToWorldPoint based on the screen width.
oh, thanks, ill try
Give it a material instead of just using the default
you need to create and assign a material to the GameObject. this is the default shader . . .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pipes : MonoBehaviour
{
void Update()
{
MovimientoTuberías();
}
private void MovimientoTuberías()
{
if (PipesController.Instance.canSpawnPipes == true)
{
transform.Translate(Vector3.left * Time.deltaTime * PipesController.Instance.speed);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "PipesDestroyPoint")
{
print("adiooooooss");
Destroy(gameObject);
}
}
}
```Does someone know why print is not being executing?
The Three Commandments of OnTriggerEnter2D:
- Thou Shalt have a 2D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 2D Rigidbody on at least one of them
bro its static
This is a static rigidbody, so it's not moving. If the other object were dynamic and moving into it, it'd work
but a static rigidbody will not send collision messages
since it doesn't move
dont procceed to add rigidbodies for all the pipes tho use only one on the bird itself 
i have rigidbody 2d in dynamic mode, where I need to translate them, and apply normal dynamic physics after. So my idea is; Set them all to kinematic mode, MovePosition to where I need, Physics2D.Simulate(0) so they move while respecting collisions without screwing with time-dependent code, then set back to dynamic mode.
Q: Would this work?
oh but the kinematic RBs wouldn’t push other things that should be dynamic…
!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.
Oh apologies
While using the unity input manager system and the ”new input system” i have 4 different players with their own player input component so they are controlled by one gamepad each, whats the approach on making a UI system which is shared between them all?
@wintry quarry In that scenario each player has their own ui system
you'd have to explain what kind of ui system you want
Like a menu that everyone can control
that's vague
there are many ways to make "a menu that everyone can control"
for example there's Super Smash Bros' characte selection screen
Sorry i will try to be more specific, imagine a player presses start: A pause menu appears, with options up to down. The first option is selected. If player 1 presses down the selected option becomes the second option, if player 2 then presses up the first option will be selected again. They all share the same menu, and the same ”pointer”
In this case you can use a regular event system and just write a custom input module that accepts inputs from any of your players
should be relatively straightforward
Aye thanks, all i needed was a point in the right direction, appreciate it
would anyone know how MovePosition works on dynamic RBs? Does it ignore the request? Or does it actually try to move
Hey really beginner question here
Im making a blink (tp) mechanic
Should I do this seperate to the controller for modularity or integrate it into the movement
If you have no intention of using it modularly outside of the player, then just integrate it.
Awesome
Wasnt sure if either way it is better practice to do it seperate
I am almost always in favor of separating
you might realize it's pretty simple to reuse the behaviour, or your original script gets huge (and later becomes messy)
I'm having a really hard time trying to edit the values of an object that I instantiate because it keeps changing the value of the prefab instead. I try to set the prefab to a gameObject in start() but I can't access it in any of my other methods, can someone please explain how this system works?
How do you get a component with the type of a specific interface?
This doesn't give me any errors, but it also just returns null:
spellType = GetComponent<ISpellType>();
A prefab is an asset file with the extension .prefab
Instantiating one uses that blueprint to create a gameobject in the scene
When you instantiate, you will get the instance as a reference
You can write:
GameObject go = Instantiate(...)
Now, the start method only runs when it is actually active in the scene, so that should not modify the prefab unless you explicitly tell it to
You may wanna show the code so we can understand what's going on better
📃 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.
Should be fine. Make sure that you actually have a component implementing that interface on your object.
**heya how do i put two .GetComponent in one instantiate line?
You may be looking at the wrong object
Thanks! I'll try using that and see where it gets me
The script that inherits from the interface is on the game object that this same script is on, so I'm not sure why it's returning null. It should be seeing it
Yeah
In here?
!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.
The damage spell script inherits from the interface im trying to get
okay, that sounds fine. are there any errors in your console that aren't caused by this thing being null?
Nope
maybe turn on Collapse and look at the first error
No errors at all
ah, you check if it's null later before using it
I'm 100% sure that the GetComponent line is the one returning null though
You should log it.
what if the raycast is failing?
you can only be 100% sure when there is an unconditionally executed line of code that tells you that it's null
right now the only way you can tell is if a raycast hits a damageable object
Yeah I had a Debug.Log(spellType); in the start method
And nothing showed up in the console line
sanity check by logging the result of GetComponent<DamageSpell>() as well
Oh smart. That DID return something
so weird
show me the definition of DamageSpell
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Spells
{
public class DamageSpell : MonoBehaviour
{
public void castSpell(GameObject particles, Vector3 targetPos)
{
Instantiate(particles, targetPos, new Quaternion());
}
}
}
That does not implement that interface.
does it have to???
It doesn't matter if you happen to have all of the methods with the right names.
what interface
Just add the interface to the class definition
DamageSpell : MonoBehaviour, IWhatever
start() {
//this below is copied twice up
GameObject HealthBar3Obj = Instantiate(HealthBar3, new Vector2(700, 450), Quaternion.identity) as GameObject;
HealthBar3Obj.transform.SetParent(CanvasObj.transform, false);
}
public GameObject getHealthBar(int playerNum)
{
Debug.Log("return health bar");
if (playerNum == 1)
return HealthBar1Obj;
if (playerNum == 2)
return HealthBar2Obj;
else
return HealthBar3Obj;
}
maybe a little explanation about how interfaces work is in order
you know how inheritance works?
I tried to instantiate the object but it wont allow me to access it within the getHealthBar() method
Ah it workie now. THanks Fen
It is locally scoped. That's why
Declare the variable in the class
just making sure you understand how it works in general, Vevy. Do you understand interfaces?
I suppose not lol
Ill look into it more. THanks yall
ok, do you know how inheritance works?
and how a class can only inherit from ONE other class in C#?
I think so
interfaces are like a way around that
do you know how abstract methods work?
where you are forced to override in a child class?
Yep
ok, an interface is like an abstract class, where every method is public abstract
AND then you are allowed to multiple inherit with them
Yeah Im aware of all that
most interfaces have like 1-4 methods tops
Im not sure how I made tha tmistake lol
see, if we only had typeclasses...
What are those
haskell typeclasses just require that you've defined a set of methods that work with a specific type. the type never explicitly "implements" a typeclass
interfaces are really useful when you have multiple classes that are pretty different, that all need to expose a similar method that does something similar
Example; I have an ISpawner, which is an interface that any sort of spawner needs to have. Specifically, methods like SomethingWeSpawnedDied, SomethingWeSpawnedDespawned, and TrySpawnSomething.
And you can slap that interface onto a spawnpoint, or a pipe from mario, or bill blaster, or whatever. The spawner class can be all sorts of different things.
But now the thing it spawns doesn’t care. It just looks for an ISpawner to report it died/despawned/etc
idk if this helps, or you already know all this
When i declare it in the class and run the code it still edits the prefab:
In a different class it tries to call the healthBarObj but it errors with "object reference not set to an instance of an object"
public void takeDamage(float damage)
{
healthAmount -= damage;
"healthbarobj"().fillAmount = 0.5f;
}
Refreshers are helpful :
:)
you should share the real line because "healthbarobj"().fillAmount = 0.5f; is obviously invalid
GameManager.GetComponent<GameManagerScript>().getHealthBar(playerNum).GetComponent<Image>().fillAmount = 0.5f;
sorry i just changed it for simplicity
Do not try to "simplify" code you are sharing.
It will just obfuscate the problem.
There's a lot going on in that line.
Any one of those steps could be failing.
yeahh
Please share !code properly. Just the whole script
📃 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.
you really should break that up into multiple lines so that you can actually determine which of the many objects on that line could be null
there are 4 separate objects just on the left hand side of the assignment operator that could potentially be null
Ok I'll spit it up and try and do some debugging
a little suggestion: you should have a Healthbar component that holds a reference to the image
GameManager should also just be a reference to GameManagerScript, not a game object
then you could write GameManager.GetHealthBar(playerNum).image.fillAmount = 0.5f;
still a mouthful, but better
you could also then give Healthbar a method to set its fill
this would be nice if you want to make the healthbar slowly go up or down
or wanted to show a number along with the bar
or many many other things
GameManager.GetHealthBar(playerNum).SetPercentage(0.5f);
this makes it very clear what the objective is
you're setting the healthbar's percentage to 50%
Hi. Working on a First Person Beat-em-up and I'm having trouble with the item grabbing system. I followed a tutorial. Everything works perfectly. The only problem is when I go to attatch the GameObject to my camera, (interact/pickup) It scales depending on my camera's rotation
Sounds like non-uniform scaling.
I wish I could send a video, but it bypasses the file size limit
you can use something like a parent constraint to make your holder object follow the camera as if it were a child without actually being a child
If an object's parent has a non-uniform scale, and the object rotates, it will get skewed as it rotates.
ok. How can I do that?
parent constraint . . .
my script makes it so that when you interact within the collider range, it teleports the object to an empty
congrats. use a parent constraint so that "empty" gameobject acts like a child of the camera
I'll try and do this, the problem I set for myself is that I have three characters that all have to have different health bars, I need to instantiate the healthbars to match the color of the character, but I need to set the parent of the healthbars to the canvas since they weren't working when I didn't... long story short, I need one code that can instantiate one canvas and three prefabs and it runs three seperate times because I have individual health managers for each of the plays... sorry if that doesn't make any sense, ive been working on this one code for a few days and its driving me a tad insane
that's pretty standard stuff.
making a dedicated Healthbar class will also make your life easier
also, I don't know what parent constraint is, so in order for me to be less of a nuisance to you, you might have to explain instead of expecting me to know everything
the healthbar can even reference a health manager
That would probably help, thank you
and then update all by itself
just ask if you don't know what something is; we don't need an apology :p
unity parent constraint
(but also consider googling, yes)
it's a component
that would be lovely, i'll try and add that, thanks for the advice!
oh ok
that's roughly what I do in the game I'm working on right now
I thought it would be some sort of an overcomplicated type of method in code or smth.
next time you see something suggested and you don't know what it is, try googling it first instead of complaining that i didn't immediately explain it to you
Sorry about that. My first experience with asking this server for help was unpleasant so I feel like everyone is yelling at me even though sometimes they aren't
Nevermind I'll move my question to #🎥┃cinemachine , unless that counts as reposting a question?
if you move your question to another channel be sure to delete it from the original channel
okay
@slender nymph would updating the m axis' on cinemachine cameras through code, be a coding channel question or a cinemachine channel question?
so you tend to have your overall controller
then subscripts for more clear code and to find things
then just call between?