2
\$\begingroup\$

I don't want the user to write a text by copying and then pasting the content to an Input Field, how can I do that?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Mind if I ask why? \$\endgroup\$ – Tyyppi_77 Aug 27 '17 at 23:17
  • \$\begingroup\$ One caution to be aware of here is that this may impact accessibility for some users who, for one reason or another, have difficulty typing text directly into your game's interface. \$\endgroup\$ – DMGregory Nov 8 '17 at 13:08
1
\$\begingroup\$

I haven't tested the following script, but I guess you can detect whether the paste keys are pressed when the value of the input changes.

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour
{
    public UnityEngine.UI.InputField mainInputField;
    private string inputValue;

    public void Start()
    {
        inputValue = mainInputField.text;
        mainInputField.onValueChanged.AddListener(OnInputValueChanged);
    }

    // Invoked when the value of the text field changes.
    public void OnInputValueChanged(string newValue)
    {
        if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && (Input.GetKey(KeyCode.V) || Input.GetKeyUp(KeyCode.V)))
        {
            Debug.LogError("Not allowed");
            mainInputField.onValueChanged.RemoveListener(OnInputValueChanged);
            mainInputField.text = inputValue;
            mainInputField.onValueChanged.AddListener(OnInputValueChanged);
        }
        else
        {
            inputValue = mainInputField.text;
        }
    }
}

EDIT : After testing this code (which works), you will have as many "Not allowed" errors as you have characters in the copied string. My solution may not be the best I guess.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.